<?php
// +----------------------------------------------------------------------
// | Tplay [ WE ONLY DO WHAT IS NECESSARY ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017 http://tplay.pengyichen.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 听雨 < 389625819@qq.com >
// +----------------------------------------------------------------------


namespace app\admin\controller;

use app\api\controller\GoogleMap;
use think\Config;
use think\Cache;
use \think\Cookie;
use \think\Controller;
use think\Exception;
use think\Session;
use think\Db;
use app\admin\model\ArticleCate as cateModel;
use app\admin\model\Trip as tripModel;
use app\admin\model\Schedule as scheduleModel;
use app\admin\model\Active as activeModel;
use app\admin\controller\Quicktrip;
use app\api\controller\KbxOther;
use app\api\controller\KbxToken;
use app\api\controller\OssController;
use app\api\controller\Trip as TripApi;
use app\api\model\Standard as SDModel;
class Trip extends User
{
    public $goodsurl='https://c.kuaibangxing.com/quick_help_wap1/#/show/';


    //定制列表【弃用 直接跳转到快速定制】
    public function index()
    {
        //跳转到快速定制
        $this->redirect(url('admin/quicktrip/index'));exit;
        $post = $this->request->post();
        //分页bug处理
        $temp_page=request()->param('page');
        if(isset($temp_page)){
            //条件从缓存取出
            $post=Cookie::get('postlist');
        }else{
            //把条件写入缓存
            Cookie::set('postlist',$post);
        }
        if (isset($post['tripname']) and !empty($post['tripname'])) {
            $where['name'] = ['like', '%' . trim($post['tripname']) . '%'];
        }
        $where['use_type'] = 2;
        $trip = Db::name('trip')->where($where)->order('create_time desc')->select();

        for($x=0 ; $x<count($trip) ; $x++){
            $admin=Db::name('admin')->where('id',$trip[$x]['adminid'])->select();
            if(!empty($admin)){
                $trip[$x]['admin']=$admin[0]['nickname'];
            }else{
                $trip[$x]['admin']="";
            }
            $trip[$x]['create_time']=date("Y-m-d H:i",$trip[$x]['create_time']);
        }
        $this->assign('trip',$trip);
        $this->assign('wherelist',$post);

        return $this->fetch();
    }

    //产品列表
    public function product()
    {
        $post = $this->request->post();
        //分页bug处理
        $temp_page=request()->param('page');
        if(isset($temp_page)){
            //条件从缓存取出
            $post=Cookie::get('postlist');
        }else{
            //把条件写入缓存
            Cookie::set('postlist',$post);
        }
        if (isset($post['tripname']) and !empty($post['tripname'])) {
            $where['name'] = ['like', '%' . trim($post['tripname']) . '%'];
        }

        $where['use_type'] = 1;
        $trip = Db::name('trip')->where($where)->order('create_time desc')->select();

        for($x=0 ; $x<count($trip) ; $x++){
            $admin=Db::name('admin')->where('id',$trip[$x]['adminid'])->select();
            if(!empty($admin)){
                $trip[$x]['admin']=$admin[0]['nickname'];
            }else{
                $trip[$x]['admin']="";
            }

            $trip[$x]['create_time']=date("Y-m-d H:i",$trip[$x]['create_time']);

            //查询是否存在FAQ
            $faq_flag = 0;
            $faq = db("faq")
                ->where("groupid",$trip[$x]['id'])
                ->where("typeid",1)
                ->where("deleted",0)
                ->find();
            if(!empty($faq)){
                $faq_flag = 1;
            }

            $trip[$x]['faq_flag'] = $faq_flag;
        }
        $this->assign('trip',$trip);
        $this->assign('wherelist',$post);
        return $this->fetch();
    }

    public function addtrip()
    {
        $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
        $use_type = $this->request->has('use_type') ? $this->request->param('use_type', 0, 'intval') : 0;
        $model=new tripModel();
        if($id > 0) {
            //修改操作
            if($this->request->isPost()) {
                //是提交操作
                $post = $this->request->post();
                //验证  唯一规则： 表名，字段名，排除主键值，主键名
                $validate = new \think\Validate([
                    ['name', 'require', '行程名称不能为空'],
                    ['days', 'require', '天数不能为空'],
                    ['people', 'require', '人数不能为空'],
                ]);
                //验证部分数据合法性
                if (!$validate->check($post)) {
                    $this->error('提交失败：' . $validate->getError());
                }
                if($post['days']<1) {
                    return $this->error('天数不能小于1');
                }
                if(!empty($post['showintroduction'])){
                    $post['showintroduction']=1;
                }else{
                    $post['showintroduction']=0;
                }
                if(!empty($post['showprice'])){
                    $post['showprice']=1;
                }else{
                    $post['showprice']=0;
                }
                if(!empty($post['showcareful'])){
                    $post['showcareful']=1;
                }else{
                    $post['showcareful']=0;
                }
                if(!empty($post['showback'])){
                    $post['showback']=1;
                }else{
                    $post['showback']=0;
                }

                if(!empty($post['show_day_map'])){
                    $post['show_day_map']=1;
                }else{
                    $post['show_day_map']=0;
                }
                if(!empty($post['sale_starttime'])){
                    $post['sale_starttime']=strtotime("2018-".$post['sale_starttime']);
                }else{
                    $post['sale_starttime']=0;
                }
                if(!empty($post['sale_endtime'])){
                    $post['sale_endtime']=strtotime("2018-".$post['sale_endtime']);
                }else{
                    $post['sale_endtime']=0;
                }

                if(false == $model->allowField(true)->save($post,['id'=>$id])) {
                    return $this->error('修改失败');
                } else {
                    return $this->success('修改成功', 'admin/menu/index');
                }
            } else {
                //非提交操作
                $where['deleted'] =0;
                $where['groupid'] = array("GT",0);
                $city = Db::name('city')->where($where)->select();

                $poi = Db::name('trip')->where('id',$id)->select();

                if($poi[0]['sale_starttime'] > 0){
                    $poi[0]['sale_starttime']=date("m-d",$poi[0]['sale_starttime']);
                }else{
                    $poi[0]['sale_starttime']='';
                }

                if($poi[0]['sale_endtime'] > 0){
                    $poi[0]['sale_endtime']=date("m-d",$poi[0]['sale_endtime']);
                }else{
                    $poi[0]['sale_endtime']='';
                }

                if($poi[0]['supplier'] > 0){
                    $supplier = Db::name('poi')->where('id',$poi[0]['supplier'])->field("groupid")->find();
                    $poi[0]['supplier_city'] = $supplier['groupid'];
                }else{
                    $poi[0]['supplier_city'] = 0;
                }

                //供应商   不能放上面，引入类构造方法会过滤html标签
                list($supplier,$supplierNameArr) = (new Product())->getSupplierList();
                $this->assign('supplier',$supplier);

                if(!empty($poi)) {
                    $this->assign('city',$city);
                    $this->assign('menu',$poi[0]);
                    $this->assign('menu1',$poi[0]);
                    return $this->fetch();
                } else {
                    return $this->error('id不正确');
                }
            }
        }else{
            //新增操作
            if($this->request->isPost()) {
                //获取管理员id
                $adminid = Cookie::get('admin');
                //是提交操作
                $post = $this->request->post();

                //验证  唯一规则： 表名，字段名，排除主键值，主键名
                $validate = new \think\Validate([
                    ['name', 'require', '行程名称不能为空'],
                    ['days', 'require', '天数不能为空'],
                    ['people', 'require', '人数不能为空'],
                ]);
                //验证部分数据合法性
                if (!$validate->check($post)) {
                    $this->error('提交失败：' . $validate->getError());
                }
                if($post['days']<1) {
                    return $this->error('天数不能小于1');
                }
                if(Db::name('trip')->where('name',$post['name'])->select()) {
                    return $this->error('行程名称已存在');
                }
                $post['adminid']=$adminid;
                if(!empty($post['showintroduction'])){
                    $post['showintroduction']=1;
                }else{
                    $post['showintroduction']=0;
                }
                if(!empty($post['showprice'])){
                    $post['showprice']=1;
                }else{
                    $post['showprice']=0;
                }
                if(!empty($post['showcareful'])){
                    $post['showcareful']=1;
                }else{
                    $post['showcareful']=0;
                }
                if(!empty($post['showback'])){
                    $post['showback']=1;
                }else{
                    $post['showback']=0;
                }
                if(!empty($post['sale_starttime'])){
                    $post['sale_starttime']=strtotime("2018-".$post['sale_starttime']);
                }else{
                    $post['sale_starttime']=0;
                }
                if(!empty($post['sale_endtime'])){
                    $post['sale_endtime']=strtotime("2018-".$post['sale_endtime']);
                }else{
                    $post['sale_endtime']=0;
                }
                if(!empty($post['start_go_time'])){
                    $post['start_go_time']=strtotime($post['start_go_time']);
                }else{
                    $post['start_go_time']=0;
                }
                $trip=$model->allowField(true)->save($post);
                $tripid=Db::name('trip')->getLastInsID();
                if(false == $trip) {
                    return $this->error('添加失败');
                } else {
                    //入库日程
                    for($y=1;$y<=$post['days'];$y++){
                        $schedule['groupid']=$tripid;
                        $schedule['displayorder']=$y;
                        if($post['start_go_time']){
                            $schedule['time'] = date("Y-m-d",strtotime("+".($y-1)."day",$post['start_go_time']));
                        }
                        $postday= Db::name('schedule')->insert($schedule);
                        if(false ==$postday) {
                            return $this->error('添加失败');
                        }
                    }
                    return $this->success('添加成功','admin/poi/index');
                }
            } else {
                $where['deleted'] =0;
                $where['groupid'] = array("GT",0);
                $city = Db::name('city')->where($where)->select();

                $menu['showintroduction']=0;
                $menu['showprice']=0;
                $menu['showcareful']=0;
                $menu['showback']=0;

                //供应商   不能放上面，引入类构造方法会过滤html标签
                list($supplier,$supplierNameArr) = (new Product())->getSupplierList();
                $this->assign('supplier',$supplier);

                $this->assign('use_type',$use_type);
                $this->assign('city',$city);
                $this->assign('menu1',$menu);
                //非提交操作
                return $this->fetch();
            }
        }
    }

    //定制行程
    public function customized()
    {
        $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;

        $day=$this->request->has('day') ? $this->request->param('day', 0, 'intval') : 1;
        $nearspots=array();
        $trip=Db::name('trip')->where('id',$id)->select();
        $schedule= Db::name('schedule')->where('groupid',$id)->order('displayorder')->select();

        if(count($schedule)<$day){
            $day=count($schedule);
        }
        if($day<1){
            $day=1;
        }

        //计算景点距离
        function getDistance($lat1, $lng1, $lat2, $lng2){
            $earthRadius = 6367000; //approximate radius of earth in meters
            $lat1 = ($lat1 * pi() ) / 180;
            $lng1 = ($lng1 * pi() ) / 180;
            $lat2 = ($lat2 * pi() ) / 180;
            $lng2 = ($lng2 * pi() ) / 180;
            $calcLongitude = $lng2 - $lng1;
            $calcLatitude = $lat2 - $lat1;
            $stepOne = pow(sin($calcLatitude / 2), 2) + cos($lat1) * cos($lat2) * pow(sin($calcLongitude / 2), 2);
            $stepTwo = 2 * asin(min(1, sqrt($stepOne)));
            $calculatedDistance = $earthRadius * $stepTwo;
            return round($calculatedDistance);
        }

        if(count($schedule)>0){
            $active= Db::name('active')->where('groupid',$schedule[$day-1]['id'])->order('displayorder')->select();
        }else{
            $active=0;
        }

        if($active){
            $poi0=array();
            foreach ($active as $key=>$value){
                $poi0= Db::name('poi')->where('id',$value['poiid'])->field('lat,lng,name')->find();
                if($poi0){
                    break;
                }
            }

            $pois= Db::name('poi')->where('deleted','0')->field('id,lat,lng,name')->select();
            if($pois&&$poi0){
                foreach($pois as $key=>$value){
                    if($value['name']!=$poi0['name']){
                        $limit = getDistance($poi0['lat'],$poi0['lng'],$value['lat'],$value['lng']);
                        if($limit<=100000){
                            array_push($nearspots,[$value['name'],round($limit/1000,1),$value['id']]);
                        }
                    }
                }
            }
        }

        $origin=0;
        $destination=0;
        $waypoints=array();
        if(count($active)>1){
            foreach($active as $key=>$value){
                if($key<(count($active)-1)){
                    $poi1= Db::name('poi')->where('id',$active[$key+1]['poiid'])->field('lat,lng')->find();
                    $poi2= Db::name('poi')->where('id',$active[$key]['poiid'])->field('lat,lng')->find();

                    if($poi1['lat']&&$poi1['lng']&&$poi2['lat']&&$poi2['lng']){
                        $limit = getDistance($poi1['lat'],$poi1['lng'],$poi2['lat'],$poi2['lng']);
                    }else{
                        $limit=0;
                    }

                    $active[$key]['limit']=round($limit/1000,1);
                }else{
                    $active[$key]['limit']=0;
                }
                $poilat=Db::name('poi')->where('id',$active[$key]['poiid'])->field('lat,lng')->find();
                if($poilat['lat']){
                    if(!$origin){
                        $origin="{lat: ".$poilat['lat'].", lng:".$poilat['lng']."}";
                    }else{
                        array_push($waypoints,[$poilat['lat'],$poilat['lng']]);
                    }
                }
            }
        }else{
            foreach($active as $key=>$value){
                $active[$key]['limit']=0;
            }
        }

        if(count($waypoints)>0){
            $destination="{lat: ".$waypoints[count($waypoints)-1][0].", lng:".$waypoints[count($waypoints)-1][1]."}";
            array_pop ($waypoints);
        }
        if(empty($trip)){
            $tripname='读取失败';
        }else{
            $tripname=$trip[0]['name'];
        }

        $use_type = $trip[0]['use_type'];
        $carType = isset($trip[0]['carType']) ? $trip[0]['carType'] : '';


        //计算总价
        $totalPrice = 0;
        foreach ($schedule as $k=>$v) {
            if(!empty($v['dayPrice'])){
                $totalPrice +=$v['dayPrice'];
            }
        }


        $this->assign('totalPrice',$totalPrice);
        $this->assign('origin',$origin);
        $this->assign('destination',$destination);
        $this->assign('waypoints',$waypoints);
        $this->assign('nearspots',$nearspots);
        $this->assign('schedule',$schedule);
        $this->assign('active',$active);
        $this->assign('tripname',$tripname);
        $this->assign('use_type',$use_type);
        $this->assign('day',$day);
        $this->assign('id',$trip[0]['id']);
        $this->assign('carType',$carType);
        return $this->fetch();

    }

    //产品定制行程
    public function pcustomized()
    {
        $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;

        $day=$this->request->has('day') ? $this->request->param('day', 0, 'intval') : 1;
        $nearspots=array();
        $trip=Db::name('trip')->where('id',$id)->select();
        $schedule= Db::name('schedule')->where('groupid',$id)->order('displayorder')->select();

        if(count($schedule)<$day){
            $day=count($schedule);
        }
        if($day<1){
            $day=1;
        }

        //计算景点距离
        function getDistance($lat1, $lng1, $lat2, $lng2){
            $earthRadius = 6367000; //approximate radius of earth in meters
            $lat1 = ($lat1 * pi() ) / 180;
            $lng1 = ($lng1 * pi() ) / 180;
            $lat2 = ($lat2 * pi() ) / 180;
            $lng2 = ($lng2 * pi() ) / 180;
            $calcLongitude = $lng2 - $lng1;
            $calcLatitude = $lat2 - $lat1;
            $stepOne = pow(sin($calcLatitude / 2), 2) + cos($lat1) * cos($lat2) * pow(sin($calcLongitude / 2), 2);
            $stepTwo = 2 * asin(min(1, sqrt($stepOne)));
            $calculatedDistance = $earthRadius * $stepTwo;
            return round($calculatedDistance);
        }

        if(count($schedule)>0){
            $active= Db::name('active')->where('groupid',$schedule[$day-1]['id'])->order('displayorder')->select();
        }else{
            $active=0;
        }

        if($active){
            $poi0=array();
            foreach ($active as $key=>$value){
                $poi0= Db::name('poi')->where('id',$value['poiid'])->field('lat,lng,name')->find();
                if($poi0){
                    break;
                }
            }

            $pois= Db::name('poi')->where('deleted','0')->field('id,lat,lng,name')->select();
            if($pois&&$poi0){
                foreach($pois as $key=>$value){
                    if($value['name']!=$poi0['name']){
                        $limit = getDistance($poi0['lat'],$poi0['lng'],$value['lat'],$value['lng']);
                        if($limit<=100000){
                            array_push($nearspots,[$value['name'],round($limit/1000,1),$value['id']]);
                        }
                    }
                }
            }
        }

        $origin=0;
        $destination=0;
        $waypoints=array();
        if(count($active)>1){
            foreach($active as $key=>$value){
                if($key<(count($active)-1)){
                    $poi1= Db::name('poi')->where('id',$active[$key+1]['poiid'])->field('lat,lng')->find();
                    $poi2= Db::name('poi')->where('id',$active[$key]['poiid'])->field('lat,lng')->find();

                    if($poi1['lat']&&$poi1['lng']&&$poi2['lat']&&$poi2['lng']){
                        $limit = getDistance($poi1['lat'],$poi1['lng'],$poi2['lat'],$poi2['lng']);
                    }else{
                        $limit=0;
                    }

                    $active[$key]['limit']=round($limit/1000,1);
                }else{
                    $active[$key]['limit']=0;
                }
                $poilat=Db::name('poi')->where('id',$active[$key]['poiid'])->field('lat,lng')->find();
                if($poilat['lat']){
                    if(!$origin){
                        $origin="{lat: ".$poilat['lat'].", lng:".$poilat['lng']."}";
                    }else{
                        array_push($waypoints,[$poilat['lat'],$poilat['lng']]);
                    }
                }
            }
        }else{
            foreach($active as $key=>$value){
                $active[$key]['limit']=0;
            }
        }

        if(count($waypoints)>0){
            $destination="{lat: ".$waypoints[count($waypoints)-1][0].", lng:".$waypoints[count($waypoints)-1][1]."}";
            array_pop ($waypoints);
        }
        if(empty($trip)){
            $tripname='读取失败';
        }else{
            $tripname=$trip[0]['name'];
        }

        $use_type=$trip[0]['use_type'];

        $this->assign('origin',$origin);
        $this->assign('destination',$destination);
        $this->assign('waypoints',$waypoints);
        $this->assign('nearspots',$nearspots);
        $this->assign('schedule',$schedule);
        $this->assign('active',$active);
        $this->assign('tripname',$tripname);
        $this->assign('use_type',$use_type);
        $this->assign('day',$day);
        $this->assign('id',$trip[0]['id']);
        return $this->fetch();

    }

    public function addcustomized()
    {
        $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
        $model=new scheduleModel();
        if($id > 0) {
            //修改操作
            if($this->request->isPost()) {
                //是提交操作
                $post = $this->request->post();
                //验证  唯一规则： 表名，字段名，排除主键值，主键名
                $validate = new \think\Validate([
                    ['title', 'require', '标题不能为空'],
                ]);
                //验证部分数据合法性
                if (!$validate->check($post)) {
                    $this->error('提交失败：' . $validate->getError());
                }

                if(!empty($post['showmap'])){
                    $post['showmap']=1;
                }else{
                    $post['showmap']=0;
                }

                if(false == $model->allowField(true)->save($post,['id'=>$id])) {
                    return $this->error('修改失败');
                } else {
                    return $this->success('修改成功', 'admin/menu/index');
                }
            } else {
                //非提交操作
                $schedule = Db::name('schedule')->where('id',$id)->select();
                if(!empty($schedule)) {
                    $this->assign('menu',$schedule[0]);
                    return $this->fetch();
                } else {
                    return $this->error('id不正确');
                }
            }
        }else{
            //新增操作
            $groupid = $this->request->has('groupid') ? $this->request->param('groupid', 0, 'intval') : 0;
            if($this->request->isPost()) {
                $post = $this->request->post();
                //验证  唯一规则： 表名，字段名，排除主键值，主键名
                $validate = new \think\Validate([
                    ['title', 'require', '标题不能为空'],
                ]);
                //验证部分数据合法性
                if (!$validate->check($post)) {
                    $this->error('提交失败：' . $validate->getError());
                }
                $schedule= Db::name('schedule')->where('groupid',$groupid)->select();

                $post['groupid']=$groupid;
                $post['displayorder']=count($schedule)+1;

                if(!empty($post['showmap'])){
                    $post['showmap']=1;
                }else{
                    $post['showmap']=0;
                }

                $schedule= Db::name('schedule')->insert($post);

                if(false == $schedule) {
                    return $this->error('添加失败');
                } else {
                    Db::table('tplay_trip')->where('id', $groupid)->update(['days' =>$post['displayorder']]);
                    return $this->success('添加成功','admin/trip/customized');
                }
            } else {
                //非提交操作
                $this->assign('groupid',$groupid);
                return $this->fetch();
            }
        }

    }

    public function addsomecustomized()
    {
        $post = $this->request->post();
        $displayorder=$post['id'];
        $groupid=$post['groupid'];
        $addday['groupid']=$groupid;
        $addday['displayorder']=$displayorder+1;

        $addschedule=Db::name('schedule')->where('groupid',$groupid)->select();

        for($x=count($addschedule) ;$x>=$addday['displayorder'];$x--){
            Db::table('tplay_schedule')->where('groupid', $groupid)->where('displayorder', $x)->update(['displayorder' =>$x+1]);
        }

        $schedule= Db::name('schedule')->insert($addday);

        if(false == $schedule) {
            return $this->error('添加失败');

        } else {
            Db::table('tplay_trip')->where('id', $groupid)->update(['days' =>count($addschedule)+1]);
            return $this->success('添加成功','admin/trip/customized');
        }
    }

    public function delcustomized()
    {
        $post = $this->request->post();
        $customizedid=$post['id'];
        $groupid=$post['groupid'];

        $schedules=Db::name('schedule')->where('groupid',$groupid)->select();
        $del=Db::name('schedule')->where('id',$customizedid)->select();
        $schedule= Db::name('schedule')->where('id',$customizedid)->delete();
        $deldisplayorder=$del[0]['displayorder'];

        for($x=$deldisplayorder+1 ;$x<=count($schedules);$x++){
            Db::table('tplay_schedule')->where('groupid', $groupid)->where('displayorder', $x)->update(['displayorder' =>$x-1]);
        }

        if(false == $schedule) {
            return $this->error('删除失败');

        } else {
            Db::table('tplay_trip')->where('id', $groupid)->update(['days' =>count($schedules)-1]);

            //修改行程城市数量
            $cityschedulegroupid=Db::name('schedule')->where('groupid',$groupid)->select();//获取和当前日程属于同一个组的日程
            $allactive=array();
            $allcity=array();
            for($x=0;$x<count($cityschedulegroupid);$x++){
                $schedulactive=Db::name('active')->where('groupid',$cityschedulegroupid[$x]['id'])->select();
                if(count($schedulactive)>0){
                    for($y=0;$y<count($schedulactive);$y++){
                        array_push($allactive,$schedulactive[$y]);
                    }
                }
            }

            if(count($allactive)>0){
                for($x=0;$x<count($allactive);$x++){
                    if($allactive[$x]['cityid']){
                        array_push($allcity,$allactive[$x]['cityid']);
                    }
                }
            }
            $citynums = array_unique($allcity);
            Db::table('tplay_trip')->where('id', $groupid)->update(['citys' =>count($citynums)]);

            return $this->success('删除成功','admin/trip/customized');
        }
    }

    public function upcustomized()
    {
        $post = $this->request->post();
        $customizedid=$post['id'];
        $groupid=$post['groupid'];

        if($customizedid>1){
            $precus=Db::name('schedule')->where('groupid',$groupid)->where('displayorder',($customizedid-1))->select();
            $thiscus=Db::name('schedule')->where('groupid',$groupid)->where('displayorder',$customizedid)->select();

            Db::table('tplay_schedule')->where('id', $precus[0]['id'])->update(['displayorder' =>$customizedid]);
            Db::table('tplay_schedule')->where('id', $thiscus[0]['id'])->update(['displayorder' =>($customizedid-1)]);

            return $this->success('修改成功','admin/trip/customized');
        }else{
            return $this->error('修改失败');
        }
    }

    public function downcustomized()
    {
        $post = $this->request->post();
        $customizedid=$post['id'];
        $groupid=$post['groupid'];
        $group=Db::name('schedule')->where('groupid',$groupid)->select();
        if($customizedid<count($group)){
            $nexcus=Db::name('schedule')->where('groupid',$groupid)->where('displayorder',($customizedid+1))->select();
            $thiscus=Db::name('schedule')->where('groupid',$groupid)->where('displayorder',$customizedid)->select();
            Db::table('tplay_schedule')->where('id', $nexcus[0]['id'])->update(['displayorder' =>$customizedid]);
            Db::table('tplay_schedule')->where('id', $thiscus[0]['id'])->update(['displayorder' =>($customizedid+1)]);

            return $this->success('修改成功','admin/trip/customized');
        }else{
            return $this->error('修改失败');
        }
    }

    //定制页添加活动
    public function addactive()
    {
        $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
        $groupid = $this->request->has('groupid') ? $this->request->param('groupid', 0, 'intval') : 0;
        $model = new activeModel();
        if($id > 0) {
            //修改操作
            if($this->request->isPost()) {
                //是提交操作
                $post = $this->request->post();
                if(!empty($post['poi_id'])){
                    $poiid=Db::name('poi')->where('id',$post['poi_id'])->where('deleted',0)->select();
                    $post['cityid']=$poiid[0]['groupid'];
                    $post['poiid']=$poiid[0]['id'];
                    $post['poiname']=$poiid[0]['name']."（".$poiid[0]['eng_name']."）";
                }else if(!empty($post['cityname'])){
                    $poiid=Db::name('city')->where('name',$post['cityname'])->where('deleted',0)->select();
                    $post['cityid']=$poiid[0]['id'];
                }else if (!empty($post['goodsid'])){
                    $goodsid=$post['goodsid'];
                    unset($post['goodsid']);
                    $goods_temp=Db::name('goods')->where(['goods_id'=>$goodsid])->field('city_id,goods_name,goods_introduce,goods_image')->find();
                    $post['title']=$goods_temp['goods_name'];
                    $post['cityid']=$goods_temp['city_id'];
                    $post['goods_id']=$goodsid;
                    $post['other_images']=$goods_temp['goods_image'];
                    //追加商品链接
                    $post['goodsurl']=$this->goodsurl.$goodsid;
                }
                if(!empty($post['showmobile'])){
                    $post['showmobile']=1;
                }else{
                    $post['showmobile']=0;
                }

                if(!empty($post['showticket'])){
                    $post['showticket']=1;
                }else{
                    $post['showticket']=0;
                }

                if(!empty($post['showopen_time'])){
                    $post['showopen_time']=1;
                }else{
                    $post['showopen_time']=0;
                }

                if(!empty($post['showticket_url'])){
                    $post['showticket_url']=1;
                }else{
                    $post['showticket_url']=0;
                }

                if(!empty($post['showeng_introduce'])){
                    $post['showeng_introduce']=1;
                }else{
                    $post['showeng_introduce']=0;
                }

                if(!empty($post['showdescription'])){
                    $post['showdescription']=1;
                }else{
                    $post['showdescription']=0;
                }

                if(!empty($post['showprice'])){
                    $post['showprice']=1;
                }else{
                    $post['showprice']=0;
                }

                if(!empty($post['showthumb'])){
                    $post['showthumb']=1;
                }else{
                    $post['showthumb']=0;
                }

                if(!empty($post['showsource'])){
                    $post['showsource']=1;
                }else{
                    $post['showsource']=0;
                }

                if(!empty($post['showaddress'])){
                    $post['showaddress']=1;
                }else{
                    $post['showaddress']=0;
                }

                if(!empty($post['showgrade'])){
                    $post['showgrade']=1;
                }else{
                    $post['showgrade']=0;
                }

                //POI门票信息
                if(!empty($post['tickit'])){
                    Db::table('tplay_poi')->where('id',$post['poi_id'])->update(['tickit' => $post['tickit']]);
                }
                if(!empty($post['tickitDetails'])){
                    Db::table('tplay_poi')->where('id',$post['poi_id'])->update(['tickitDetails' => $post['tickitDetails']]);
                }

                unset($post['tickit']);
                unset($post['tickitDetails']);

                //增加接送机title
                if($post['typeid']==1){
                    $airType = $post['portType']=='Transport_Vehicle_FromAirport' ? "接机": "送机";
                    $post['title'] = $post['cityname'].$airType;
                }

                if(false == $model->allowField(true)->save($post,['id'=>$id])) {
                    return $this->error('修改失败');
                } else {
                    $activegroupid=Db::name('active')->where('id',$id)->select();
                    //修改行程城市数量
                    $cityscheduleid=Db::name('schedule')->where('id',$activegroupid[0]['groupid'])->select();//新增当前活动对应的日程ID
                    $cityschedulegroupid=Db::name('schedule')->where('groupid',$cityscheduleid[0]['groupid'])->select();//获取和当前日程属于同一个组的日程
                    $allactive=array();
                    $allcity=array();
                    for($x=0;$x<count($cityschedulegroupid);$x++){
                        $schedulactive=Db::name('active')->where('groupid',$cityschedulegroupid[$x]['id'])->select();
                        if(count($schedulactive)>0){
                            for($y=0;$y<count($schedulactive);$y++){
                                array_push($allactive,$schedulactive[$y]);
                            }
                        }
                    }

                    if(count($allactive)>0){
                        for($x=0;$x<count($allactive);$x++){
                            if($allactive[$x]['cityid']){
                                array_push($allcity,$allactive[$x]['cityid']);
                            }
                        }
                    }
                    $citynums = array_unique($allcity);
                    Db::table('tplay_trip')->where('id', $cityscheduleid[0]['groupid'])->update(['citys' =>count($citynums)]);

                    //统计城市
                    $quicktrip = new Quicktrip();
                    $quicktrip->countCity($cityscheduleid[0]['groupid']);

                    return $this->success('修改成功', 'admin/menu/index');
                }
            } else {
                //非提交操作
                $active = Db::name('active')->where('id',$id)->select();
                if(!empty($active)) {
                    $activepoitype=$active[0]['poitype'];
                    $citys = Db::name('city')->where('type','CITY')->where('deleted',0)->select();
                    if(!empty($active[0]['cityid'])){
                        if($activepoitype==1){
                            $citypoi=Db::name('poi')->where('typeid','eq',1)->where('deleted',0)->where('groupid',$active[0]['cityid'])->select();
                        }elseif($activepoitype==2){
                            $citypoi=Db::name('poi')->where('typeid','eq',5)->where('deleted',0)->where('groupid',$active[0]['cityid'])->select();
                        }elseif($activepoitype==3){
                            $citypoi=Db::name('poi')->where('typeid','in',[2,3,4,6])->where('deleted',0)->where('groupid',$active[0]['cityid'])->select();
                        }else{
                            $citypoi=Db::name('poi')->where('typeid','lt',7)->where('deleted',0)->where('groupid',$active[0]['cityid'])->select();
                        }
                    }else{
                        if($activepoitype==1){
                            $citypoi=Db::name('poi')->where('typeid','eq',1)->where('deleted',0)->where('groupid',$citys[0]['id'])->select();
                        }elseif($activepoitype==2){
                            $citypoi=Db::name('poi')->where('typeid','eq',5)->where('deleted',0)->where('groupid',$citys[0]['id'])->select();
                        }elseif($activepoitype==3){
                            $citypoi=Db::name('poi')->where('typeid','in',[2,3,4,6])->where('deleted',0)->where('groupid',$citys[0]['id'])->select();
                        }else{
                            $citypoi=Db::name('poi')->where('typeid','lt',7)->where('deleted',0)->where('groupid',$citys[0]['id'])->select();
                        }
                    }

                    $poiImg = [];
                    $poiImgValue = '';
                    if(!empty($active[0]['poiid'])){
                        $tickitData = Db::name('poi')->where('id',$active[0]['poiid'])->field("thumb,tickit,tickitDetails")->find();
                        $active[0]['tickit'] = isset($tickitData['tickit']) ? $tickitData['tickit'] : '';
                        $active[0]['tickitDetails'] = isset($tickitData['tickitDetails']) ? $tickitData['tickitDetails'] : '';

                        $poi_thumb = !empty($active[0]['poiImg']) ? $active[0]['poiImg'] : $tickitData['thumb'];
                        if(!empty($poi_thumb)){
                            $poi_thumbArr = explode(",",$poi_thumb);
                            $poi_thumbArr = array_filter($poi_thumbArr);
                            $img1 = array_shift($poi_thumbArr);
                            $img2 = array_shift($poi_thumbArr);
                            if(!empty($img1)){
                                $poiImg[] = $img1;
                            }
                            if(!empty($img2)){
                                $poiImg[] = $img2;
                            }
                        }

                        $poiImgValue = implode(",",$poiImg);
                    }


                    //其他  已上传图片
                    $otherimages=$active[0]['other_images'];
                    $otherimages=explode(',',$otherimages);


                    $airportPlaceData = [];
                    $goodslit = [];

                    $typeid = $active[0]['typeid'];
                    if($typeid==1){//机场
                        //获取机场
                        $airportData = Db::name('city')->where('id',$active[0]['cityid'])->field("name")->find();
                        $airportPlace = $this->kbxGetAirport($airportData['name']);
                        $airportPlaceData = $airportPlace['data'];
                    }elseif($typeid==6){
                        $goodslit = Db::name('goods')->field('goods_id,goods_name')->limit(20)->select();
                    }

                    //POI名称更换为 中+英
                    foreach ($citypoi as $k=>$v) {
                        $citypoi[$k]['name'] = $v['name']."（".$v['eng_name']."）";
                    }

                    $this->assign('poiImgValue',$poiImgValue);
                    $this->assign('poiImg',$poiImg);
                    $this->assign('goods',$goodslit);
                    $this->assign('otherimages',$otherimages);
                    $this->assign('groupid',$groupid);
                    $this->assign('city',$citys);
                    $this->assign('citypoi',$citypoi);
                    $this->assign('airportPlace',$airportPlaceData);
                    $this->assign('menu',$active[0]);
                    $this->assign('typeid',$active[0]['typeid']);

                    return $this->fetch();
                } else {
                    return $this->error('id不正确');
                }
            }
        }else{
            //新增操作
            if($this->request->isPost()) {
                $post = $this->request->post();
                if(!empty($post['poi_id'])){
                    $poiid=Db::name('poi')->where('id',$post['poi_id'])->select();
                    $post['cityid']=$poiid[0]['groupid'];
                    $post['poiid']=$poiid[0]['id'];
                    $post['poiname']=$poiid[0]['name']."（".$poiid[0]['eng_name']."）";
                }else if(!empty($post['cityname'])){
                    $poiid=Db::name('city')->where('name',$post['cityname'])->select();
                    $post['cityid']=$poiid[0]['id'];
                }else if (!empty($post['goodsid'])){
                    $goodsid=$post['goodsid'];
                    unset($post['goodsid']);
                    $goods_temp=Db::name('goods')->where(['goods_id'=>$goodsid])->field('city_id,goods_name,goods_introduce,goods_image')->find();
                    $post['title']=$goods_temp['goods_name'];
                    $post['cityid']=$goods_temp['city_id'];
                    $post['goods_id']=$goodsid;
                    $post['other_images']=$goods_temp['goods_image'];
                    //追加商品链接
                    $post['goodsurl']=$this->goodsurl.$goodsid;
                }

                if(!empty($post['showmobile'])){
                    $post['showmobile']=1;
                }else{
                    $post['showmobile']=0;
                }

                if(!empty($post['showticket'])){
                    $post['showticket']=1;
                }else{
                    $post['showticket']=0;
                }

                if(!empty($post['showopen_time'])){
                    $post['showopen_time']=1;
                }else{
                    $post['showopen_time']=0;
                }

                if(!empty($post['showticket_url'])){
                    $post['showticket_url']=1;
                }else{
                    $post['showticket_url']=0;
                }

                if(!empty($post['showeng_introduce'])){
                    $post['showeng_introduce']=1;
                }else{
                    $post['showeng_introduce']=0;
                }

                if(!empty($post['showdescription'])){
                    $post['showdescription']=1;
                }else{
                    $post['showdescription']=0;
                }

                if(!empty($post['showprice'])){
                    $post['showprice']=1;
                }else{
                    $post['showprice']=0;
                }

                if(!empty($post['showthumb'])){
                    $post['showthumb']=1;
                }else{
                    $post['showthumb']=0;
                }

                if(!empty($post['showsource'])){
                    $post['showsource']=1;
                }else{
                    $post['showsource']=0;
                }

                if(!empty($post['showaddress'])){
                    $post['showaddress']=1;
                }else{
                    $post['showaddress']=0;
                }

                if(!empty($post['showgrade'])){
                    $post['showgrade']=1;
                }else{
                    $post['showgrade']=0;
                }

                $active= Db::name('active')->where('groupid',$groupid)->select();
                $post['displayorder']=count($active)+1;


                //POI门票信息
                if(!empty($post['tickit'])){
                    Db::table('tplay_poi')->where('id',$post['poi_id'])->update(['tickit' => $post['tickit']]);
                }
                if(!empty($post['tickitDetails'])){
                    Db::table('tplay_poi')->where('id',$post['poi_id'])->update(['tickitDetails' => $post['tickitDetails']]);
                }

                unset($post['tickit']);
                unset($post['tickitDetails']);


                //增加接送机title
                if($post['typeid']==1){
                    $airType = $post['portType']=='Transport_Vehicle_FromAirport' ? "接机": "送机";
                    $post['title'] = $post['cityname'].$airType;
                }

                if(false ==  $model->allowField(true)->save($post)) {
                    return $this->error('添加失败');
                } else {
                    //修改行程城市数量
                    $cityscheduleid=Db::name('schedule')->where('id',$groupid)->select();//新增当前活动对应的日程ID
                    $cityschedulegroupid=Db::name('schedule')->where('groupid',$cityscheduleid[0]['groupid'])->select();//获取和当前日程属于同一个组的日程
                    $allactive=array();
                    $allcity=array();
                    for($x=0;$x<count($cityschedulegroupid);$x++){
                        $schedulactive=Db::name('active')->where('groupid',$cityschedulegroupid[$x]['id'])->select();
                        if(count($schedulactive)>0){
                            for($y=0;$y<count($schedulactive);$y++){
                                array_push($allactive,$schedulactive[$y]);
                            }
                        }
                    }

                    if(count($allactive)>0){
                        for($x=0;$x<count($allactive);$x++){
                            if($allactive[$x]['cityid']){
                                array_push($allcity,$allactive[$x]['cityid']);
                            }
                        }
                    }

                    $citynums = array_unique($allcity);
                    Db::table('tplay_trip')->where('id', $cityscheduleid[0]['groupid'])->update(['citys' =>count($citynums)]);

                    //统计城市
                    $quicktrip = new Quicktrip();
                    $quicktrip->countCity($cityscheduleid[0]['groupid']);

                    return $this->success('添加成功','admin/trip/customized');
                }
            } else {
                //非提交操作
                $this->assign('groupid',$groupid);
                $list=session::get('checkcityname');

                $menu['id']=$id;
                $menu['cityname']=$list;
                $menu['time']='';
                $menu['mapmark']='';
                $menu['poiname']='';
                $menu['showmobile']='';
                $menu['showticket']='';
                $menu['showopen_time']='';
                $menu['showticket_url']='';
                $menu['showeng_introduce']='';
                $menu['showdescription']='';
                $menu['showprice']='';
                $menu['showthumb']='';
                $menu['showsource']='';
                $menu['showaddress']='';
                $menu['showgrade']='';
                $menu['title']='';
                $menu['content']='';
                $menu['poitype']='';
                $menu['poiid']='';
                $menu['airportPlace']='';
                $menu['portType']='';
                $menu['arrival_time']='';
                $menu['poiImg']='';

                $poiImgValue='';
                $poiImg = [];

                $citys = Db::name('city')->where('type','CITY')->where('deleted',0)->select();

                if(!empty($list)){
                    $sessioncity=Db::name('city')->where('name',$list)->where('deleted',0)->find();
                    if($sessioncity){
                        $airportpoi=Db::name('poi')->where('typeid','eq',7)->where('deleted',0)->where('groupid',$sessioncity['id'])->select();
                        $citypoi=Db::name('poi')->where('typeid','eq',1)->where('deleted',0)->where('groupid',$sessioncity['id'])->select();
                    }else{
                        $airportpoi=Db::name('poi')->where('typeid','eq',7)->where('deleted',0)->where('groupid',$citys[0]['id'])->select();
                        $citypoi=Db::name('poi')->where('typeid','eq',1)->where('deleted',0)->where('groupid',$citys[0]['id'])->select();
                    }
                }else{
                    $airportpoi=Db::name('poi')->where('typeid','eq',7)->where('deleted',0)->where('groupid',$citys[0]['id'])->select();
                    $citypoi=Db::name('poi')->where('typeid','eq',1)->where('deleted',0)->where('groupid',$citys[0]['id'])->select();
                }

                $menu['tickit'] = isset($citypoi[0]['tickit']) ? $citypoi[0]['tickit'] : '';
                $menu['tickitDetails'] = isset($citypoi[0]['tickitDetails']) ? $citypoi[0]['tickitDetails'] : '';

                //获取机场
                $airportData = Db::name('city')->where('id',$citys[0]['id'])->field("name")->find();
                $airportPlace = $this->kbxGetAirport($airportData['name']);

                //POI名称更换为 中+英
                foreach ($citypoi as $k=>$v) {
                    $citypoi[$k]['name'] = $v['name']."（".$v['eng_name']."）";
                }

                if(!empty($citypoi[0]['thumb'])){
                    $poi_thumbArr = explode(",",$citypoi[0]['thumb']);
                    $poi_thumbArr = array_filter($poi_thumbArr);
                    $img1 = array_shift($poi_thumbArr);
                    $img2 = array_shift($poi_thumbArr);
                    if(!empty($img1)){
                        $poiImg[] = $img1;
                    }
                    if(!empty($img2)){
                        $poiImg[] = $img2;
                    }

                    $poiImgValue = implode(",",$poiImg);
                }

                $goodslit=Db::name('goods')->field('goods_id,goods_name')->limit(20)->select();
                $this->assign('poiImgValue',$poiImgValue);
                $this->assign('poiImg',$poiImg);
                $this->assign('goods',$goodslit);
                $this->assign('city',$citys);
                $this->assign('citypoi',$citypoi);
                $this->assign('menu',$menu);
                $this->assign('showticket',"1");
                $this->assign('showmobile',"1");
                $this->assign('airportpoi',$airportpoi);
                $this->assign('airportPlace',$airportPlace['data']);

                return $this->fetch();
            }
        }
    }

    //产品页添加活动
    public function addpactive()
    {
        $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
        $groupid = $this->request->has('groupid') ? $this->request->param('groupid', 0, 'intval') : 0;
        $model=new activeModel();
        if($id > 0) {
            //修改操作
            if($this->request->isPost()) {
                //是提交操作
                $post = $this->request->post();
                if(!empty($post['poi_id'])){
                    $poiid=Db::name('poi')->where('id',$post['poi_id'])->where('deleted',0)->select();
                    $post['cityid']=$poiid[0]['groupid'];
                    $post['poiid']=$poiid[0]['id'];
                    $post['poiname']=$poiid[0]['name']."（".$poiid[0]['eng_name']."）";
                }else if(!empty($post['cityname'])){
                    $poiid=Db::name('city')->where('name',$post['cityname'])->where('deleted',0)->select();
                    $post['cityid']=$poiid[0]['id'];
                }else if (!empty($post['goodsid'])){
                    $goodsid=$post['goodsid'];
                    unset($post['goodsid']);
                    $goods_temp=Db::name('goods')->where(['goods_id'=>$goodsid])->field('goods_name,goods_introduce,goods_image')->find();
                    $post['title']=$goods_temp['goods_name'];
                    $post['other_images']=$goods_temp['goods_image'];
                    //追加商品链接
                    $post['goodsurl']=$this->goodsurl.$goodsid;
                }

                $active= Db::name('active')->where('groupid',$groupid)->select();
                if(!empty($post['showmobile'])){
                    $post['showmobile']=1;
                }else{
                    $post['showmobile']=0;
                }

                if(!empty($post['showticket'])){
                    $post['showticket']=1;
                }else{
                    $post['showticket']=0;
                }

                if(!empty($post['showopen_time'])){
                    $post['showopen_time']=1;
                }else{
                    $post['showopen_time']=0;
                }

                if(!empty($post['showticket_url'])){
                    $post['showticket_url']=1;
                }else{
                    $post['showticket_url']=0;
                }

                if(!empty($post['showeng_introduce'])){
                    $post['showeng_introduce']=1;
                }else{
                    $post['showeng_introduce']=0;
                }

                if(!empty($post['showdescription'])){
                    $post['showdescription']=1;
                }else{
                    $post['showdescription']=0;
                }

                if(!empty($post['showprice'])){
                    $post['showprice']=1;
                }else{
                    $post['showprice']=0;
                }

                if(!empty($post['showthumb'])){
                    $post['showthumb']=1;
                }else{
                    $post['showthumb']=0;
                }

                if(!empty($post['showsource'])){
                    $post['showsource']=1;
                }else{
                    $post['showsource']=0;
                }

                if(!empty($post['showaddress'])){
                    $post['showaddress']=1;
                }else{
                    $post['showaddress']=0;
                }

                if(!empty($post['showgrade'])){
                    $post['showgrade']=1;
                }else{
                    $post['showgrade']=0;
                }

                if(false == $model->allowField(true)->save($post,['id'=>$id])) {
                    return $this->error('修改失败');
                } else {
                    $activegroupid=Db::name('active')->where('id',$id)->select();
                    //修改行程城市数量
                    $cityscheduleid=Db::name('schedule')->where('id',$activegroupid[0]['groupid'])->select();//新增当前活动对应的日程ID
                    $cityschedulegroupid=Db::name('schedule')->where('groupid',$cityscheduleid[0]['groupid'])->select();//获取和当前日程属于同一个组的日程
                    $allactive=array();
                    $allcity=array();
                    for($x=0;$x<count($cityschedulegroupid);$x++){
                        $schedulactive=Db::name('active')->where('groupid',$cityschedulegroupid[$x]['id'])->select();
                        if(count($schedulactive)>0){
                            for($y=0;$y<count($schedulactive);$y++){
                                array_push($allactive,$schedulactive[$y]);
                            }
                        }
                    }

                    if(count($allactive)>0){
                        for($x=0;$x<count($allactive);$x++){
                            if($allactive[$x]['cityid']){
                                array_push($allcity,$allactive[$x]['cityid']);
                            }
                        }
                    }
                    $citynums = array_unique($allcity);
                    Db::table('tplay_trip')->where('id', $cityscheduleid[0]['groupid'])->update(['citys' =>count($citynums)]);

                    $schedule="";
                    $allschedule=array();
                    $actives=Db::name('active')->where('groupid',$activegroupid[0]['groupid'])->select();
                    if(count($actives)>0){
                        for($x=0;$x<count($actives);$x++){
                            if($actives[$x]['cityid']){
                                array_push($allschedule,$actives[$x]['cityid']);
                            }
                        }
                    }
                    $schedulecitynums = array_unique($allschedule);

                    if(count($schedulecitynums)>0){
                        foreach ($schedulecitynums as $key => $value){
                            $schedulecityname=Db::name('city')->where('id',$value)->select();
                            $schedule.=",".$schedulecityname[0]['name'];
                        }
                    }

                    Db::table('tplay_schedule')->where('id', $activegroupid[0]['groupid'])->update(['title' =>$schedule]);

                    $trip = db("trip")
                        ->alias("t")
                        ->join('schedule s','s.groupid=t.id')
                        ->join('active a','s.id=a.groupid')
                        ->where("a.id",$id)
                        ->field("t.id")
                        ->find();
                    //统计城市
                    $quicktrip = new Quicktrip();
                    $quicktrip->countCity($trip['id']);

                    return $this->success('修改成功', 'admin/menu/index');
                }
            } else {
                //非提交操作
                $active = Db::name('active')->where('id',$id)->select();
                if(!empty($active)) {
                    $activepoitype=$active[0]['poitype'];
                    $citys = Db::name('city')->where('type','CITY')->where('deleted',0)->select();
                    if(!empty($active[0]['cityid'])){
                        $airportpoi=Db::name('poi')->where('typeid','eq',7)->where('deleted',0)->where('groupid',$active[0]['cityid'])->select();
                        if($activepoitype==1){
                            $citypoi=Db::name('poi')->where('typeid','eq',1)->where('deleted',0)->where('groupid',$active[0]['cityid'])->select();
                        }elseif($activepoitype==2){
                            $citypoi=Db::name('poi')->where('typeid','eq',5)->where('deleted',0)->where('groupid',$active[0]['cityid'])->select();
                        }elseif($activepoitype==3){
                            $citypoi=Db::name('poi')->where('typeid','in',[2,3,4,6])->where('deleted',0)->where('groupid',$active[0]['cityid'])->select();
                        }else{
                            $citypoi=Db::name('poi')->where('typeid','lt',7)->where('deleted',0)->where('groupid',$active[0]['cityid'])->select();
                        }
                    }else{
                        $airportpoi=Db::name('poi')->where('typeid','eq',7)->where('deleted',0)->where('groupid',$citys[0]['id'])->select();
                        if($activepoitype==1){
                            $citypoi=Db::name('poi')->where('typeid','eq',1)->where('deleted',0)->where('groupid',$citys[0]['id'])->select();
                        }elseif($activepoitype==2){
                            $citypoi=Db::name('poi')->where('typeid','eq',5)->where('deleted',0)->where('groupid',$citys[0]['id'])->select();
                        }elseif($activepoitype==3){
                            $citypoi=Db::name('poi')->where('typeid','in',[2,3,4,6])->where('deleted',0)->where('groupid',$citys[0]['id'])->select();
                        }else{
                            $citypoi=Db::name('poi')->where('typeid','lt',7)->where('deleted',0)->where('groupid',$citys[0]['id'])->select();
                        }
                    }

                    $poiImg = [];
                    $poiImgValue = '';
                    if(!empty($active[0]['poiid'])){
                        $tickitData = Db::name('poi')->where('id',$active[0]['poiid'])->field("thumb,tickit,tickitDetails")->find();
                        $poi_thumb = !empty($active[0]['poiImg']) ? $active[0]['poiImg'] : $tickitData['thumb'];
                        if(!empty($poi_thumb)){
                            $poi_thumbArr = explode(",",$poi_thumb);
                            $poi_thumbArr = array_filter($poi_thumbArr);
                            $img1 = array_shift($poi_thumbArr);
                            $img2 = array_shift($poi_thumbArr);
                            if(!empty($img1)){
                                $poiImg[] = $img1;
                            }
                            if(!empty($img2)){
                                $poiImg[] = $img2;
                            }
                        }

                        $poiImgValue = implode(",",$poiImg);
                    }

                    //其他  已上传图片
                    $otherimages=$active[0]['other_images'];
                    $otherimages=explode(',',$otherimages);

                    $goodslit=Db::name('goods')->field('goods_id,goods_name')->limit(20)->select();

                    //POI名称更换为 中+英
                    foreach ($citypoi as $k=>$v) {
                        $citypoi[$k]['name'] = $v['name']."（".$v['eng_name']."）";
                    }

                    $this->assign('goods',$goodslit);
                    $this->assign('poiImgValue',$poiImgValue);
                    $this->assign('poiImg',$poiImg);
                    $this->assign('otherimages',$otherimages);
                    $this->assign('groupid',$groupid);
                    $this->assign('city',$citys);
                    $this->assign('citypoi',$citypoi);
                    $this->assign('airportpoi',$airportpoi);
                    $this->assign('menu',$active[0]);
                    $this->assign('typeid',$active[0]['typeid']);

                    return $this->fetch();
                } else {
                    return $this->error('id不正确');
                }
            }
        }else{
            //新增操作
            if($this->request->isPost()) {
                $post = $this->request->post();
                if(!empty($post['poi_id'])){
                    $poiid=Db::name('poi')->where('id',$post['poi_id'])->select();
                    $post['cityid']=$poiid[0]['groupid'];
                    $post['poiid']=$poiid[0]['id'];
                    $post['poiname']=$poiid[0]['name']."（".$poiid[0]['eng_name']."）";
                }else if(!empty($post['cityname'])){
                    $poiid=Db::name('city')->where('name',$post['cityname'])->select();
                    $post['cityid']=$poiid[0]['id'];
                }else if (!empty($post['goodsid'])){
                    $goodsid=$post['goodsid'];
                    unset($post['goodsid']);
                    $goods_temp=Db::name('goods')->where(['goods_id'=>$goodsid])->field('goods_name,goods_introduce,goods_image')->find();
                    $post['title']=$goods_temp['goods_name'];
                    $post['other_images']=$goods_temp['goods_image'];
                    //追加商品链接
                    $post['goodsurl']=$this->goodsurl.$goodsid;
                }

                if(!empty($post['showmobile'])){
                    $post['showmobile']=1;
                }else{
                    $post['showmobile']=0;
                }

                if(!empty($post['showticket'])){
                    $post['showticket']=1;
                }else{
                    $post['showticket']=0;
                }

                if(!empty($post['showopen_time'])){
                    $post['showopen_time']=1;
                }else{
                    $post['showopen_time']=0;
                }

                if(!empty($post['showticket_url'])){
                    $post['showticket_url']=1;
                }else{
                    $post['showticket_url']=0;
                }

                if(!empty($post['showeng_introduce'])){
                    $post['showeng_introduce']=1;
                }else{
                    $post['showeng_introduce']=0;
                }

                if(!empty($post['showdescription'])){
                    $post['showdescription']=1;
                }else{
                    $post['showdescription']=0;
                }

                if(!empty($post['showprice'])){
                    $post['showprice']=1;
                }else{
                    $post['showprice']=0;
                }

                if(!empty($post['showthumb'])){
                    $post['showthumb']=1;
                }else{
                    $post['showthumb']=0;
                }

                if(!empty($post['showsource'])){
                    $post['showsource']=1;
                }else{
                    $post['showsource']=0;
                }

                if(!empty($post['showaddress'])){
                    $post['showaddress']=1;
                }else{
                    $post['showaddress']=0;
                }

                if(!empty($post['showgrade'])){
                    $post['showgrade']=1;
                }else{
                    $post['showgrade']=0;
                }

                $active= Db::name('active')->where('groupid',$groupid)->select();
                $post['displayorder']=count($active)+1;

                if(false ==  $model->allowField(true)->save($post)) {
                    return $this->error('添加失败');
                } else {
                    //修改行程城市数量
                    $cityscheduleid=Db::name('schedule')->where('id',$groupid)->select();//新增当前活动对应的日程ID
                    $cityschedulegroupid=Db::name('schedule')->where('groupid',$cityscheduleid[0]['groupid'])->select();//获取和当前日程属于同一个组的日程
                    $allactive=array();
                    $allcity=array();
                    for($x=0;$x<count($cityschedulegroupid);$x++){
                        $schedulactive=Db::name('active')->where('groupid',$cityschedulegroupid[$x]['id'])->select();
                        if(count($schedulactive)>0){
                            for($y=0;$y<count($schedulactive);$y++){
                                array_push($allactive,$schedulactive[$y]);
                            }
                        }
                    }

                    if(count($allactive)>0){
                        for($x=0;$x<count($allactive);$x++){
                            if($allactive[$x]['cityid']){
                                array_push($allcity,$allactive[$x]['cityid']);
                            }
                        }
                    }

                    $citynums = array_unique($allcity);
                    Db::table('tplay_trip')->where('id', $cityscheduleid[0]['groupid'])->update(['citys' =>count($citynums)]);

                    $schedule="";
                    $allschedule=array();
                    $actives=Db::name('active')->where('groupid',$groupid)->select();

                    if(count($actives)>0){
                        for($x=0;$x<count($actives);$x++){
                            if($actives[$x]['cityid']){
                                array_push($allschedule,$actives[$x]['cityid']);
                            }
                        }
                    }

                    $schedulecitynums = array_unique($allschedule);
                    if(count($schedulecitynums)>0){
                        foreach ($schedulecitynums as $key => $value){
                            $schedulecityname=Db::name('city')->where('id',$value)->select();
                            $schedule.=",".$schedulecityname[0]['name'];
                        }
                    }

                    Db::table('tplay_schedule')->where('id', $groupid)->update(['title' =>$schedule]);

                    //统计城市
                    $quicktrip = new Quicktrip();
                    $quicktrip->countCity($cityscheduleid[0]['groupid']);

                    return $this->success('添加成功','admin/trip/customized');
                }
            } else {
                //非提交操作
                $this->assign('groupid',$groupid);
                $list=session::get('checkcityname');

                $menu['id']=$id;
                $menu['cityname']=$list;
                $menu['time']='';
                $menu['mapmark']='';
                $menu['poiname']='';
                $menu['showmobile']='';
                $menu['showticket']='';
                $menu['showopen_time']='';
                $menu['showticket_url']='';
                $menu['showeng_introduce']='';
                $menu['showdescription']='';
                $menu['showprice']='';
                $menu['showthumb']='';
                $menu['showsource']='';
                $menu['showaddress']='';
                $menu['showgrade']='';
                $menu['title']='';
                $menu['content']='';
                $menu['poitype']='';
                $menu['poiid']='';
                $menu['poiImg']='';

                $poiImgValue='';
                $poiImg = [];

                $citys = Db::name('city')->where('type','CITY')->where('deleted',0)->select();

                if(!empty($list)){
                    $sessioncity=Db::name('city')->where('name',$list)->where('deleted',0)->find();
                    if($sessioncity){
                        $airportpoi=Db::name('poi')->where('typeid','eq',7)->where('deleted',0)->where('groupid',$sessioncity['id'])->select();
                        $citypoi=Db::name('poi')->where('typeid','eq',1)->where('deleted',0)->where('groupid',$sessioncity['id'])->select();
                    }else{
                        $airportpoi=Db::name('poi')->where('typeid','eq',7)->where('deleted',0)->where('groupid',$citys[0]['id'])->select();
                        $citypoi=Db::name('poi')->where('typeid','eq',1)->where('deleted',0)->where('groupid',$citys[0]['id'])->select();
                    }
                }else{
                    $airportpoi=Db::name('poi')->where('typeid','eq',7)->where('deleted',0)->where('groupid',$citys[0]['id'])->select();
                    $citypoi=Db::name('poi')->where('typeid','eq',1)->where('deleted',0)->where('groupid',$citys[0]['id'])->select();
                }

                $goodslit=Db::name('goods')->field('goods_id,goods_name')->limit(20)->select();

                //POI名称更换为 中+英
                foreach ($citypoi as $k=>$v) {
                    $citypoi[$k]['name'] = $v['name']."（".$v['eng_name']."）";
                }

                if(!empty($citypoi[0]['thumb'])){
                    $poi_thumbArr = explode(",",$citypoi[0]['thumb']);
                    $poi_thumbArr = array_filter($poi_thumbArr);
                    $img1 = array_shift($poi_thumbArr);
                    $img2 = array_shift($poi_thumbArr);
                    if(!empty($img1)){
                        $poiImg[] = $img1;
                    }
                    if(!empty($img2)){
                        $poiImg[] = $img2;
                    }

                    $poiImgValue = implode(",",$poiImg);
                }

                $this->assign('goods',$goodslit);
                $this->assign('poiImgValue',$poiImgValue);
                $this->assign('poiImg',$poiImg);
                $this->assign('city',$citys);
                $this->assign('citypoi',$citypoi);
                $this->assign('menu',$menu);
                $this->assign('showticket',"1");
                $this->assign('showmobile',"1");
                $this->assign('airportpoi',$airportpoi);

                return $this->fetch();
            }
        }
    }

    public function delactive()
    {
        $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
        $groupid=Db::name('active')->where('id',$id)->select();
        if(false == Db::name('active')->where('id',$id)->delete()) {
            return $this->error('删除失败');
        } else {
            //修改行程城市数量
            $cityscheduleid=Db::name('schedule')->where('id',$groupid[0]['groupid'])->select();//新增当前活动对应的日程ID
            $cityschedulegroupid=Db::name('schedule')->where('groupid',$cityscheduleid[0]['groupid'])->select();//获取和当前日程属于同一个组的日程
            $allactive=array();
            $allcity=array();
            for($x=0;$x<count($cityschedulegroupid);$x++){
                $schedulactive=Db::name('active')->where('groupid',$cityschedulegroupid[$x]['id'])->select();
                if(count($schedulactive)>0){
                    for($y=0;$y<count($schedulactive);$y++){
                        array_push($allactive,$schedulactive[$y]);
                    }
                }
            }

            if(count($allactive)>0){
                for($x=0;$x<count($allactive);$x++){
                    if($allactive[$x]['cityid']){
                        array_push($allcity,$allactive[$x]['cityid']);
                    }
                }
            }

            $citynums = array_unique($allcity);

            Db::table('tplay_trip')->where('id', $cityscheduleid[0]['groupid'])->update(['citys' =>count($citynums)]);

            //修改后续的活动displayorder
            $alledtactive=Db::name('active')->where('groupid',$groupid[0]['groupid'])->select();

            for($x=0;$x<count($alledtactive);$x++){
                if($alledtactive[$x]['displayorder']>$groupid[0]['displayorder']){
                    Db::table('tplay_active')->where('id',$alledtactive[$x]['id'])->update(['displayorder' =>($alledtactive[$x]['displayorder']-1)]);
                }
            }

            //统计城市
            $quicktrip = new Quicktrip();
            $quicktrip->countCity($cityscheduleid[0]['groupid']);

            return $this->success('删除成功','admin/poi/index');
        }
    }

    public function upactive()
    {
        $post = $this->request->post();
        $groupid=$post['groupid'];
        $orderid=$post['orderid'];

        if($orderid>1){
            $precus=Db::name('active')->where('groupid',$groupid)->where('displayorder',($orderid-1))->select();
            $thiscus=Db::name('active')->where('groupid',$groupid)->where('displayorder',$orderid)->select();
            Db::table('tplay_active')->where('id', $precus[0]['id'])->update(['displayorder' =>$orderid]);
            Db::table('tplay_active')->where('id', $thiscus[0]['id'])->update(['displayorder' =>($orderid-1)]);

            return $this->success('修改成功','admin/trip/customized');
        }else{
            return $this->error('修改失败');
        }
    }

    public function downactive()
    {
        $post = $this->request->post();
        $groupid=$post['groupid'];
        $orderid=$post['orderid'];
        $group=Db::name('active')->where('groupid',$groupid)->select();
        if($orderid<count($group)){
            $nexcus=Db::name('active')->where('groupid',$groupid)->where('displayorder',($orderid+1))->select();
            $thiscus=Db::name('active')->where('groupid',$groupid)->where('displayorder',$orderid)->select();
            Db::table('tplay_active')->where('id', $nexcus[0]['id'])->update(['displayorder' =>$orderid]);
            Db::table('tplay_active')->where('id', $thiscus[0]['id'])->update(['displayorder' =>($orderid+1)]);

            return $this->success('修改成功','admin/trip/customized');
        }else{
            return $this->error('修改失败');
        }
    }

    public function selectpoi()
    {
        $post = $this->request->post();
        $cityname= $post['name'];
        $poitype= $post['poitype'];
        $cityid=Db::name('city')->where('name',$cityname)->select();
        session::set('checkcityname', $cityname);
        $typeid= $post['typeid'];
        if($typeid==7){
            $selectpoi=Db::name('poi')->where('deleted',0)->where('groupid',$cityid[0]['id'])->where('typeid',$typeid)->select();
        }elseif($typeid==8){
            $selectpoi=Db::name('poi')->where('deleted',0)->where('groupid',$cityid[0]['id'])->where('typeid',$typeid)->select();
        }else{
            if ($poitype == 1) {
                $selectpoi = Db::name('poi')->where('deleted',0)->where('groupid', $cityid[0]['id'])->where('typeid', 'eq', 1)->select();
            } elseif ($poitype == 2) {
                $selectpoi = Db::name('poi')->where('deleted',0)->where('groupid', $cityid[0]['id'])->where('typeid', 'eq', 5)->select();
            } else {
                $selectpoi = Db::name('poi')->where('deleted',0)->where('groupid', $cityid[0]['id'])->where('typeid', 'in', [2, 3, 4, 6])->select();
            }
        }

        //POI名称更换为 中+英
        foreach ($selectpoi as $k=>$v) {
            $selectpoi[$k]['name'] = $v['name']."（".$v['eng_name']."）";
        }

        return $this->success('查询结果','',$selectpoi);
    }

    public function addpoi()
    {
        $model = new cateModel();
        $cate = $model->select();
        $cates = $model->catelist($cate);
        $this->assign('cates',$cates);
        return $this->fetch();
    }

    public function combination()
    {
        $use_type = $this->request->has('use_type') ? $this->request->param('use_type', 0, 'intval') : 0;

        if($this->request->isPost()) {
            $tripids = $this->request->has('tripids') ? $this->request->param('tripids') : '';
            $model=new tripModel();
            if($tripids){
                //获取管理员id
                $adminid = Cookie::get('admin');
                //是提交操作
                $post = $this->request->post();

                //验证  唯一规则： 表名，字段名，排除主键值，主键名
                $validate = new \think\Validate([
                    ['name', 'require', '行程名称不能为空'],
                    ['people', 'require', '人数不能为空'],
                ]);
                //验证部分数据合法性
                if (!$validate->check($post)) {
                    $this->error('提交失败：' . $validate->getError());
                }

                if(Db::name('trip')->where('name',$post['name'])->select()) {
                    return $this->error('行程名称已存在');
                }

                $post['adminid']=$adminid;
                $post['days']=1;
                unset($post['tripids']);

                if(!empty($post['showintroduction'])){
                    $post['showintroduction']=1;
                }else{
                    $post['showintroduction']=0;
                }

                if(!empty($post['showprice'])){
                    $post['showprice']=1;
                }else{
                    $post['showprice']=0;
                }

                if(!empty($post['showcareful'])){
                    $post['showcareful']=1;
                }else{
                    $post['showcareful']=0;
                }

                if(!empty($post['showback'])){
                    $post['showback']=1;
                }else{
                    $post['showback']=0;
                }

                Db::startTrans(); //启动事务
                try {
                    $trip=$model->allowField(true)->save($post);
                    $tripid=Db::name('trip')->getLastInsID();
                    $days=0;
                    $schedulenum=1;
                    $ids=explode(',',$tripids);
                    foreach ($ids as $key=>$value){
                        $getschedule= Db::name("schedule")->where(['groupid' => $value])->order("displayorder asc")->select();
                        $days+=count($getschedule);
                        foreach ($getschedule as $k=>$v) {
                            $tempnowscheduleid = $v['id'];
                            unset($v['id']);
                            $v['groupid'] = $tripid;
                            $v['displayorder'] = $schedulenum;
                            $schedulenum+=1;
                            $v['create_time'] = time();
                            $v['update_time'] = time();

                            //插入日程数据
                            Db::name('schedule')->insert($v);
                            $newscheduleid=Db::name('schedule')->getLastInsID();
                            if ($newscheduleid) {
                                $getactive= Db::name("active")->where(['groupid' => $tempnowscheduleid])->order("displayorder asc")->select();
                                foreach ($getactive as $m=>$n) {
                                    unset($n['id']);
                                    $n['groupid'] = $newscheduleid;
                                    $n['create_time'] = time();
                                    $n['update_time'] = time();
                                    //插入日程数据
                                    Db::name('active')->insert($n);
                                }
                            }
                        }
                    }

                    $post['days']=$days;
                    $model->allowField(true)->save($post,['id'=>$tripid]);

                    Db::commit(); //提交事务
                    return $this->success('组合成功');
                } catch (\PDOException $e) {
                    Db::rollback(); //回滚事务
                    return $this->error('组合失败');
                }
            }else{
                return $this->error('组合失败');
            }
        }else{
            $trip = Db::name('trip')->order('create_time desc')->select();
            $this->assign('use_type',$use_type);
            $this->assign('trip',$trip);
            return $this->fetch();
        }
    }

    public function addcombination()
    {
        if($this->request->isPost()) {
            $tripids = $this->request->has('tripids') ? $this->request->param('tripids') : '';
            $tripid = $this->request->has('id') ? $this->request->param('id') : '';
            $model=new tripModel();
            if($tripids){
                //获取管理员id
                $adminid = Cookie::get('admin');
                //是提交操作
                $post = $this->request->post();
                Db::startTrans(); //启动事务
                try {
                    $getoldschedule= Db::name("schedule")->where(['groupid' => $tripid])->select();
                    $getdays= Db::name("trip")->where(['id' => $tripid])->field('days')->find();
                    $getdays=$getdays['days'];
                    $schedulenum=count($getoldschedule);
                    $ids=explode(',',$tripids);
                    foreach ($ids as $key=>$value){
                        $getschedule= Db::name("schedule")->where(['groupid' => $value])->order("displayorder asc")->select();
                        $getdays+=count($getschedule);
                        foreach ($getschedule as $k=>$v) {
                            $tempnowscheduleid = $v['id'];
                            unset($v['id']);
                            $v['groupid'] = $tripid;

                            $schedulenum+=1;
                            $v['displayorder'] = $schedulenum;
                            $v['create_time'] = time();
                            $v['update_time'] = time();

                            //插入日程数据
                            Db::name('schedule')->insert($v);
                            $newscheduleid=Db::name('schedule')->getLastInsID();
                            if ($newscheduleid) {
                                $getactive= Db::name("active")->where(['groupid' => $tempnowscheduleid])->order("displayorder asc")->select();
                                foreach ($getactive as $m=>$n) {
                                    unset($n['id']);
                                    $n['groupid'] = $newscheduleid;
                                    $n['create_time'] = time();
                                    $n['update_time'] = time();
                                    //插入日程数据
                                    Db::name('active')->insert($n);
                                }
                            }
                        }
                    }

                    $post['days']=$getdays;
                    $model->allowField(true)->save($post,['id'=>$tripid]);

                    Db::commit(); //提交事务
                    return $this->success('组合成功');
                } catch (\PDOException $e) {
                    Db::rollback(); //回滚事务
                    return $this->error('组合失败');
                }
            }else{
                return $this->error('组合失败');
            }
        }else{
            $id = $this->request->has('id') ? $this->request->param('id') : '';
            $trip = Db::name('trip')->where('id','neq',$id)->order('create_time desc')->select();
            $this->assign('trip',$trip);
            $this->assign('id',$id);
            return $this->fetch();
        }
    }

    public function copytrip()
    {
        $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
        $use_type = $this->request->has('use_type') ? $this->request->param('use_type', 0, 'intval') : 0;
        $adminid = Cookie::get('admin');
        if ($id) {
            //获取需要查询的trip数据
            $gettrip= \think\Db::name("trip")->where(['id' => $id])->find();
            if($gettrip['id']) {
                //查询到了trip数据var_dump($gettrip['id']);
                unset($gettrip['id']);
                $gettrip['name'] .= '的副本';
                $gettrip['create_time'] = time();
                $gettrip['update_time'] = time();
                $gettrip['adminid'] = $adminid;
                $gettrip['use_type'] = $use_type;

                $id2=\think\Db::name('trip')->insert($gettrip);
                $newtripid=Db::name('trip')->getLastInsID();

                if ($id2) {
                    $getschedule= \think\Db::name("schedule")->where(['groupid' => $id])->select();
                    foreach ($getschedule as $k=>$v) {
                        $tempnowscheduleid = $v['id'];
                        unset($v['id']);
                        $v['groupid'] = $newtripid;
                        $v['create_time'] = time();
                        $v['update_time'] = time();
                        //插入日程数据
                        Db::name('schedule')->insert($v);
                        $newscheduleid=Db::name('schedule')->getLastInsID();
                        if ($newscheduleid) {
                            $getactive= \think\Db::name("active")->where(['groupid' => $tempnowscheduleid])->select();
                            foreach ($getactive as $m=>$n) {
                                unset($n['id']);
                                $n['groupid'] = $newscheduleid;
                                $n['create_time'] = time();
                                $n['update_time'] = time();

                                //插入日程数据
                                Db::name('active')->insert($n);
                            }
                        }
                    }
                }
                return $this->success('复制成功','admin/poi/index');
            } else {
                return $this->error('复制失败');
            }
        }
        else {
            return $this->error('复制失败');
        }
    }

    public function deltrip()
    {
        $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
        if(false == Db::name('trip')->where('id',$id)->delete()) {
            return $this->error('删除失败');
        } else {
            return $this->success('删除成功','admin/poi/index');
        }
    }

    public function activesee()
    {

        $typeid = $this->request->has('typeid') ? $this->request->param('typeid', 0, 'intval') : 0;
        $id = $this->request->has('id') ? $this->request->param('id') : "";
        $nearspots=array();
        $post = $this->request->post();
        if ($id) {
            $where['id'] = $id;
        }
        $where['deleted']=0;

        //计算景点距离
        function getDistance($lat1, $lng1, $lat2, $lng2){
            $earthRadius = 6367000; //approximate radius of earth in meters
            $lat1 = ($lat1 * pi() ) / 180;
            $lng1 = ($lng1 * pi() ) / 180;
            $lat2 = ($lat2 * pi() ) / 180;
            $lng2 = ($lng2 * pi() ) / 180;
            $calcLongitude = $lng2 - $lng1;
            $calcLatitude = $lat2 - $lat1;
            $stepOne = pow(sin($calcLatitude / 2), 2) + cos($lat1) * cos($lat2) * pow(sin($calcLongitude / 2), 2);
            $stepTwo = 2 * asin(min(1, sqrt($stepOne)));
            $calculatedDistance = $earthRadius * $stepTwo;
            return round($calculatedDistance);
        }

        if($typeid){
            $poi=Db::name('poi')->where($where)->where("typeid",'eq',$typeid)->order('create_time desc')->select();
        }else{
            $poi=Db::name('poi')->where($where)->where("typeid",'lt',7)->order('create_time desc')->select();
        }

        $spots=Db::name('poi')->where("typeid",'eq',1)->select();
        $poiall=Db::name('poi')->where($where)->where("typeid",'lt',7)->select();

        $spotsnum=0;
        $experiencenum=0;
        $shownum=0;
        $townnum=0;
        $hotelnum=0;
        $othernum=0;
        $allnum=count($poiall);
        for($x=0;$x<count($poiall);$x++){
            if($poiall[$x]['typeid']==1){
                $spotsnum+=1;
            }else if($poiall[$x]['typeid']==2){
                $experiencenum+=1;
            }else if($poiall[$x]['typeid']==3){
                $shownum+=1;
            }else if($poiall[$x]['typeid']==4){
                $townnum+=1;
            }else if($poiall[$x]['typeid']==5){
                $hotelnum+=1;
            }else if($poiall[$x]['typeid']==6){
                $othernum+=1;
            }
        }

        for($x=0;$x<count($poi);$x++){
            if($poi[$x]['typeid']==1){
                $poi[$x]['type']="景点";
            }else if($poi[$x]['typeid']==2){
                $poi[$x]['type']="体验项目";
            }else if($poi[$x]['typeid']==3){
                $poi[$x]['type']="演出赛事";
            }else if($poi[$x]['typeid']==4){
                $poi[$x]['type']="限时活动";
            }else if($poi[$x]['typeid']==5){
                $poi[$x]['type']="酒店";
            }else if($poi[$x]['typeid']==6){
                $poi[$x]['type']="其他";
            }else{
                $poi[$x]['type']="";
            }

            $poi[$x]['update_time']=date("Y-m-d H:i", $poi[$x]['update_time']);
        }

        if($poi){
            $poiname=$poi[0]['name'];
            $poieng_name=$poi[0]['eng_name'];
            $latlng=[$poi[0]['lat'],$poi[0]['lng']];
            $description=$poi[0]['description'];
            $mobile=$poi[0]['mobile'];
            $ticket=$poi[0]['ticket'];
            $introduce=$poi[0]['introduce'];
            $open_time=$poi[0]['open_time'];
            $source=$poi[0]['source'];
            $address=$poi[0]['address'];
            $grade=$poi[0]['grade'];
            for($x=0;$x<count($spots);$x++){
                if($spots[$x]['name']!=$poiname){
                    $limit = getDistance($poi[0]['lat'],$poi[0]['lng'],$spots[$x]['lat'],$spots[$x]['lng']);
                    if($limit<=100000){
                        array_push($nearspots,[$spots[$x]['name'],round($limit/1000,1),$spots[$x]['id']]);
                    }
                }
            }
            $thumb=explode(',',$poi[0]['thumb']);
        }else{
            $latlng=0;
            $description='';
            $poiname='';
            $poieng_name='';
            $mobile='';
            $ticket='';
            $introduce='';
            $open_time='';
            $source='';
            $address='';
            $grade='';
            $nearspots='';
            $thumb='';
        }

        $this->assign('poiname',$poiname);
        $this->assign('poieng_name',$poieng_name);
        $this->assign('id',$id);
        $this->assign('poi',$poi);
        $this->assign('latlng',$latlng);
        $this->assign('description',$description);
        $this->assign('mobile',$mobile);
        $this->assign('ticket',$ticket);
        $this->assign('grade',$grade);
        $this->assign('introduce',$introduce);
        $this->assign('open_time',$open_time);
        $this->assign('source',$source);
        $this->assign('address',$address);
        $this->assign('nearspots',$nearspots);
        $this->assign('thumb',$thumb);
        $this->assign('allnum',$allnum);
        $this->assign('spotsnum',$spotsnum);
        $this->assign('experiencenum',$experiencenum);
        $this->assign('shownum',$shownum);
        $this->assign('townnum',$townnum);
        $this->assign('hotelnum',$hotelnum);
        $this->assign('othernum',$othernum);
        return $this->fetch();
    }

    public function preview()
    {
        $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
        $trip = Db::name('trip')->find($id);
        if(empty($id) || empty($trip)) return $this->error('对不起，该定制行程有误');
        $allcityIds = $allcitys = $allcityLatLngs = [];
        $schedules = Db::name('schedule')->where('groupid',$id)->order('displayorder')->select();
        $schedule_ids = array_column($schedules,"id");
        if(!empty($schedule_ids)){
            $actives = db('active a')
                ->join("city c","c.id=a.cityid",'left')
                ->join("poi p","p.id=a.poiid",'left')
                ->join("schedule s","a.groupid=s.id",'left')
                ->field("a.*,c.lat as c_lat,c.lng as c_lng,c.eng_name as cityEngName,
                p.introduce as p_introduce,p.lat,p.lng,p.thumb as poi_thumb,p.eng_introduce,
                p.open_time,p.ticket,p.price,p.grade,p.description,p.thumb,p.source,p.mobile,
                p.ticket_url,p.address,p.eng_name as poiengname")
                ->where(['a.groupid'=>['in',$schedule_ids]])
                ->order('s.displayorder,a.displayorder')
                ->select();
        }else{
            $actives = [];
        }
        $showpwd = $this->request->has('prevadminpwd') ? $this->request->get('prevadminpwd') : 0;
        if($showpwd){
            $this->assign('showpwd',$showpwd);
        }
        //地图地址优化
        $trip['thumb_map_img'] = (new OssController())->getOssThumbImg($trip['thumb_map_img'],640,400);
        //默认值为空
        foreach ($schedules as $key=>$value){
            //地图地址优化
            $schedules[$key]['thumb_map_img'] = (new OssController())->getOssThumbImg($value['thumb_map_img'],640,400);
            $schedules[$key]['child'] = [];
            $schedules[$key]['citys'] = [];
        }

        foreach ($actives as $key=>$value){
            //所有城市经纬度
            $cityLatLng = [
                'lat'=>floatval($value['c_lat']),
                'lng'=>floatval($value['c_lng']),
                'id'=>$value['cityid'],
                'type'=>'city',
                'name'=>$value['cityname'],
                'eng_name'=>$value['cityEngName'],
            ];
            //判断最后一个是否和当前的城市重合
            //if(end($allcityLatLngs)!=$cityLatLng){
            //    array_push($allcityLatLngs,$cityLatLng);
            //}
            //判断城市列表中是否已经存在
            if(!empty($value['cityid']) && !in_array($value['cityid'],$allcityIds)){
                array_push($allcityLatLngs,$cityLatLng);
                array_push($allcityIds,$value['cityid']);
            }
            //去除重复的城市
            if(!empty($value['cityname'])){
                array_push($allcitys,$value['cityname']."(".$value['cityEngName'].")");
            }
            //城市去重
            $allcitys = array_unique($allcitys);

            if(empty($value['poiImg'])){
                $value['thumb'] = '';
            }else{
                $value['thumb'] = $value['poiImg'];
            }
            $thumb_img_arr = [];
            if(!empty($value['thumb'])){
                $thumb_img_arr = array_filter(explode(',',$value['thumb']));
                foreach ($thumb_img_arr as $thumb_key=>$thumb_value){
                    $thumb_img_arr[$thumb_key] = (new OssController())->getOssThumbImg($thumb_value,360,240);
                }
            }
            $value['thumb'] = $thumb_img_arr;
            //其他图片
            if(!empty($value['other_images'])){
                $imageArr = explode(",",$value['other_images']);
                $imageArr = array_filter($imageArr);
                foreach ($imageArr as $image_key=>$image_value){
                    $imageArr[$image_key] = (new OssController())->getOssThumbImg($image_value,360,240);
                }
                $value['image_arr'] = $imageArr;
            }else{
                $value['image_arr'] = [];
            }
            $value['name_id'] = "name_".$value['id'];
            $city_name = "";
            if(!empty($value['poiname'])){
                $city_name = $value['poiname'];
            }elseif(!empty($value['cityname'])){
                $city_name = $value['cityname'];
            }elseif(!empty($value['title'])){
                $city_name =$value['title'];
            }
            $value['ticket'] = empty($trip['showticket'])?"":$value['ticket'];
            $value['open_time'] = empty($trip['showopen_time'])?"":$value['open_time'];
            $value['ticket_url'] = empty($trip['showticket_url'])?"":$value['ticket_url'];
            $value['eng_introduce'] = empty($trip['showeng_introduce'])?"":$value['eng_introduce'];
            $value['description'] = empty($trip['showdescription'])?"":$value['description'];
            $value['price'] = empty($trip['showprice'])?"":$value['price'];
            $value['poiImg'] = empty($trip['showthumb'])?"":$value['poiImg'];
            $value['source'] = empty($trip['showsource'])?"":$value['source'];
            $value['address'] = empty($trip['showaddress'])?"":$value['address'];
            $value['grade'] = empty($trip['showgrade'])?"":$value['grade'];
            $value['mobile'] = empty($trip['showmobile'])?"":$value['mobile'];
            $value['poi_content'] = empty($value['poi_content'])?$value['p_introduce']:$value['poi_content'];

            if($value['activeType']==2 || $value['activeType']==3){
                $value['ticket'] = '';
                $value['open_time'] = '';
                $value['ticket_url'] = '';
                $value['eng_introduce'] = '';
                $value['description'] = '';
                $value['price'] = '';
                $value['poiImg'] = '';
                $value['source'] = '';
                $value['address'] = '';
                $value['grade'] = '';
                $value['mobile'] = '';
                $value['poi_content'] = '';
                $value['image_arr'] = '';
                $value['thumb'] = '';
            }

            //封装结构
            foreach ($schedules as $k=>$v){
                if($v['id']==$value['groupid']){
                    $schedules[$k]['child'][] = $value;
                    if(!empty($city_name)){
                        $schedules[$k]['citys'][] = $city_name;
                    }
                    break;
                }
            }
        }

        foreach($schedules as $key=>$value){
            $daytitle  = $value['title'];
            if($value['title']!==""){
                if(substr($value['title'],0,1)==","){
                    $daytitle = substr($value['title'],1);
                }
            }
            $activeKeyArr=[];
            foreach ($value['child'] as $k=>$v){
                if($v['showkey']==1){
                    if($v['typeid']==3){
                        $keytitle = $v['poiname'];
                    }elseif($v['typeid']==2){
                        $keytitle = $v['cityname'];
                    }else{
                        $keytitle = $v['title'];
                    }

                    $activeKeyArr[] = [
                        'id'=>"name_".$v['id'],
                        'title'=>$keytitle,
                    ];
                }
            }
            $keyArr[] = [
                'day' => "DAY".($key+1)."：",
                'daytitle' => $daytitle,
                'day_key' => "day_".($key+1),
                'active' => $activeKeyArr,
                'day_description'=>$value['day_description']
            ];
            //经纬度
            $schedules[$key]['hasLine'] = false;

            if(!empty($value['thumb_map_img']) && $trip['show_day_map']==1) {
                $schedules[$key]['hasLine'] = true;
            }
        }
        $admin=db('admin')->find($trip['adminid']);
        if(!empty($admin)){
            $trip['admin']=$admin['nickname'];
            $trip['wx_qrcode']=$admin['wx_qrcode'];
        }else{
            $trip['admin']="";
            $trip['wx_qrcode']="";
        }

        $http = 'http://';
        if(isset($_SERVER['HTTPS']) && $_SERVER['HTTPS']=='on'){
            $http = 'https://';
        }

        $adminid= Cookie::get('admin');
        if(!empty($adminid)){
            $adminpwd=Db::name('admin')->where('id',$adminid)->select();
            $this->assign('url',$http.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'].'?prevadminpwd='.$adminpwd[0]['password']);
            $this->assign('pageurl',$http.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'].'?prevadminpwd='.$adminpwd[0]['password']);
            $this->assign('pwd',$adminpwd[0]['password']);
            $this->assign('wordurl',$http.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'].'?prevadminpwd='.$adminpwd[0]['password']);
        }else{
            $prevadminpwd=$_GET['prevadminpwd'];
            $this->assign('url',$http.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
            $this->assign('pwd',$prevadminpwd);
            $this->assign('wordurl',$http.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
        }
        $this->assign('baseurl',$http.$_SERVER['HTTP_HOST']);
        $this->assign('testbaseurl','https://'.$_SERVER['HTTP_HOST']);
        $this->assign('name',$trip['name']);
        $this->assign('allcity',$allcitys);
        $this->assign('scheduletime',[$schedules[0]['time'],$schedules[count($schedules)-1]['time']]);
        $this->assign('trip',$trip);
        $this->assign('keyArr',$keyArr);
        $this->assign('schedules',$schedules);
        //判断城市地图是否绘制

        $hasLine = false;
        if($trip['show_city_map']==1 && !empty($trip['thumb_map_img'])){
            $hasLine  = true;
        }
        $this->assign('hasLine',$hasLine);

        $activeTypeList = (new TripApi())->getGlobalActiveTypeList(false);
        $this->assign('activeTypeList',$activeTypeList);
        return $this->fetch();
    }
    //手动更新预览地图
    public function updateGoogleMapRoad()
    {
        $post = request()->post();
        $id = $post['id']??0;
        $trip = db('trip')->find($id);
        if(empty($id) || empty($trip)) return $this->error('定制行程有误');

        $schedules = db('schedule')->where(['groupid'=>$id])->order('displayorder')->select();
        if(empty($schedules)) return $this->error('定制行程暂未添加日程');
        $scheduleids = array_column($schedules,'id');
        $actives = db('active a')
            ->join("city c", "c.id=a.cityid", 'left')
            ->join("poi p", "p.id=a.poiid", 'left')
            ->join("schedule s", "a.groupid=s.id", 'left')
            ->field("a.id,a.title,a.groupid,a.activeType,
            a.time as startingTime,a.content as remark,a.displayorder,
            a.poiid,a.cityid as cityId,c.name as cityName,
            c.kbx_id as kbxCityId,a.airport_lat,a.airport_lng,
            p.lat,p.lng,p.name as poiname,p.address,
            p.place_id,a.ticket_status,a.ticket_json,a.flight,c.lat as city_lat,c.lng as city_lng")
            ->where(['a.groupid' => ['in', $scheduleids]])
            ->order('s.displayorder,a.displayorder')
            ->select();
        if(empty($actives)) return $this->error('定制行程暂未添加日程节点');
        //接送机的经纬度从订单系统获取
        $allCityIds = [];
        $allCityLatLngs = [];
        $allCityNames = [];
        foreach ($schedules as $s_k=>$s_v){
            $schedules[$s_k]['child'] = [];
            $schedules[$s_k]['roadName'] = [];
            $schedules[$s_k]['roadMap'] = [];
            foreach ($actives as $a_k=>$a_v){
                if($s_v['id']==$a_v['groupid']){
                    $v = (new SDModel())->getAirportInfo($a_v);
                    $v['title'] = empty($v['poiname'])?$v['title']:$v['poiname'];
                    //准备经纬度
                    if(in_array($v['activeType'],[2,3])){
                        $v['lat'] = $v['airport_lat'];
                        $v['lng'] = $v['airport_lng'];
                    }
                    if(!empty($v['cityId']) && !in_array($v['cityId'],$allCityIds)){
                        array_push($allCityIds,$a_v['cityId']);
                        array_push($allCityNames,$a_v['cityName']);
                        array_push($allCityLatLngs,[
                            'lat'=>$v['city_lat'],
                            'lng'=>$v['city_lng']
                        ]);
                    }
                    $schedules[$s_k]['child'][] = $v;
                    if(!empty($v['lat']) && !empty($v['lng'])){
                        $schedules[$s_k]['roadName'][] = $v['title'];
                        $schedules[$s_k]['roadMap'][] = [
                            'lat'=>$v['lat'],
                            'lng'=>$v['lng']
                        ];
                    }
                    //匹配成 删除该节点
                    unset($actives[$a_k]);
                }
            }
        }
        //判断是否有节点
        if(empty($allCityIds)) return $this->error('请先添加城市节点');
        db::startTrans();
        try{
            //保存总地图
            $cityMapImg = (new GoogleMap())->getGoogleMapRoadImageByLatLngs($allCityLatLngs);
            foreach ($allCityNames as $ckey=>$cname){
                $allCityNames[$ckey] = ($ckey+1).'.'.$cname;
            }
            $cityMapName = implode(" | ",$allCityNames);

            db('trip')->where('id',$id)->update(['thumb_map_img'=>$cityMapImg,'thumb_map_name'=>$cityMapName]);
            foreach ($schedules as $s_k=>$s_v){
                if(!empty($s_v['roadMap'])){
                    $dayMapImg = (new GoogleMap())->getGoogleMapRoadImageByLatLngs($s_v['roadMap']);
                    foreach ($s_v['roadName'] as $rkey=>$rname){
                        $s_v['roadName'][$rkey] = ($rkey+1).'.'.$rname;
                    }
                    $dayMapName = implode(" | ",$s_v['roadName']);
                    db('schedule')->where('id',$s_v['id'])->update(['thumb_map_img'=>$dayMapImg,'thumb_map_name'=>$dayMapName]);

                }
            }

            db::commit();
            return $this->success('更新成功');
        }catch (Exception $e){
            db::rollback();
            return $this->error('更新失败,失败原因：'.$e->getMessage());
        }

    }

    //合作商可见的预览
    public function partnerpreview()
    {
        $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
        $showpwd = $this->request->has('prevadminpwd') ? $this->request->get('prevadminpwd') : 0;
        if($showpwd){
            $this->assign('showpwd',$showpwd);
        }
        $trip = Db::name('trip')->find($id);
        //需要验证权限才能查看
        $admin = Cookie::get('admin');
        if(empty($id) || empty($trip)) return $this->error('对不起，该定制行程有误');
        $tripAdminInfo = db('admin')->where('id',$trip['adminid'])->find();
        $adminInfo = db('admin')->where('id',$admin)->find();
        if($tripAdminInfo['company_id']!==$adminInfo['company_id'] && empty($trip['is_template']) && empty($showpwd)){
            //非下载情况 仅定制师自己可查看该定制
            return $this->error('对不起，暂无查看权限');
        }
        $allcityIds = $allcitys = $allcityLatLngs = [];
        $schedules = Db::name('schedule')->where('groupid',$id)->order('displayorder')->select();
        $schedule_ids = array_column($schedules,"id");
        if(!empty($schedule_ids)){
            $actives = db('active a')
                ->join("city c","c.id=a.cityid",'left')
                ->join("poi p","p.id=a.poiid",'left')
                ->join("schedule s","a.groupid=s.id",'left')
                ->field("a.*,c.lat as c_lat,c.lng as c_lng,c.eng_name as cityEngName,
                p.introduce as p_introduce,p.lat,p.lng,p.thumb as poi_thumb,p.eng_introduce,
                p.open_time,p.ticket,p.price,p.grade,p.description,p.thumb,p.source,p.mobile,
                p.ticket_url,p.address,p.eng_name as poiengname")
                ->where(['a.groupid'=>['in',$schedule_ids]])
                ->order('s.displayorder,a.displayorder')
                ->select();
        }else{
            $actives = [];
        }

        //地图地址优化
        $trip['thumb_map_img'] = (new OssController())->getOssThumbImg($trip['thumb_map_img'],640,400);
        //默认值为空
        foreach ($schedules as $key=>$value){
            //地图地址优化
            $schedules[$key]['thumb_map_img'] = (new OssController())->getOssThumbImg($value['thumb_map_img'],640,400);
            $schedules[$key]['child'] = [];
            $schedules[$key]['citys'] = [];
        }
        foreach ($actives as $key=>$value){
            //所有城市经纬度
            $cityLatLng = [
                'lat'=>floatval($value['c_lat']),
                'lng'=>floatval($value['c_lng']),
                'id'=>$value['cityid'],
                'type'=>'city',
                'name'=>$value['cityname'],
                'eng_name'=>$value['cityEngName'],
            ];
            //判断最后一个是否和当前的城市重合
            //if(end($allcityLatLngs)!=$cityLatLng){
            //    array_push($allcityLatLngs,$cityLatLng);
            //}
            //判断城市列表中是否已经存在
            if(!empty($value['cityid']) && !in_array($value['cityid'],$allcityIds)){
                array_push($allcityLatLngs,$cityLatLng);
                array_push($allcityIds,$value['cityid']);
            }
            //去除重复的城市
            if(!empty($value['cityname'])){
                array_push($allcitys,$value['cityname']."(".$value['cityEngName'].")");
            }
            //城市去重
            $allcitys = array_unique($allcitys);

            if(empty($value['poiImg'])){
                $value['thumb'] = '';
            }else{
                $value['thumb'] = $value['poiImg'];
            }
            $thumb_img_arr = [];
            if(!empty($value['thumb'])){
                $thumb_img_arr = array_filter(explode(',',$value['thumb']));
                foreach ($thumb_img_arr as $thumb_key=>$thumb_value){
                    $thumb_img_arr[$thumb_key] = (new OssController())->getOssThumbImg($thumb_value,360,240);
                }
            }
            $value['thumb'] = $thumb_img_arr;
            $value['name_id'] = "name_".$value['id'];
            //其他图片
            if(!empty($value['other_images'])){
                $imageArr = explode(",",$value['other_images']);
                $imageArr = array_filter($imageArr);
                foreach ($imageArr as $image_key=>$image_value){
                    $imageArr[$image_key] = (new OssController())->getOssThumbImg($image_value,360,240);
                }
                $value['image_arr'] = $imageArr;
            }else{
                $value['image_arr'] = [];
            }
            $value['name_id'] = "name_".$value['id'];
            $city_name = "";
            if(!empty($value['poiname'])){
                $city_name = $value['poiname'];
            }elseif(!empty($value['cityname'])){
                $city_name = $value['cityname'];
            }elseif(!empty($value['title'])){
                $city_name =$value['title'];
            }
            $value['ticket'] = empty($trip['showticket'])?"":$value['ticket'];
            $value['open_time'] = empty($trip['showopen_time'])?"":$value['open_time'];
            $value['ticket_url'] = empty($trip['showticket_url'])?"":$value['ticket_url'];
            $value['eng_introduce'] = empty($trip['showeng_introduce'])?"":$value['eng_introduce'];
            $value['description'] = empty($trip['showdescription'])?"":$value['description'];
            $value['price'] = empty($trip['showprice'])?"":$value['price'];
            $value['poiImg'] = empty($trip['showthumb'])?"":$value['poiImg'];
            $value['source'] = empty($trip['showsource'])?"":$value['source'];
            $value['address'] = empty($trip['showaddress'])?"":$value['address'];
            $value['grade'] = empty($trip['showgrade'])?"":$value['grade'];
            $value['mobile'] = empty($trip['showmobile'])?"":$value['mobile'];
            $value['poi_content'] = empty($value['poi_content'])?$value['p_introduce']:$value['poi_content'];

            if($value['activeType']==2 || $value['activeType']==3){
                $value['ticket'] = '';
                $value['open_time'] = '';
                $value['ticket_url'] = '';
                $value['eng_introduce'] = '';
                $value['description'] = '';
                $value['price'] = '';
                $value['poiImg'] = '';
                $value['source'] = '';
                $value['address'] = '';
                $value['grade'] = '';
                $value['mobile'] = '';
                $value['poi_content'] = '';
                $value['image_arr'] = '';
                $value['thumb'] = '';
            }

            //封装结构
            foreach ($schedules as $k=>$v){
                if($v['id']==$value['groupid']){
                    $schedules[$k]['child'][] = $value;
                    if(!empty($city_name)){
                        $schedules[$k]['citys'][] = $city_name;
                    }
                    break;
                }
            }
        }

        foreach($schedules as $key=>$value){
            $daytitle  = $value['title'];
            if($value['title']!==""){
                if(substr($value['title'],0,1)==","){
                    $daytitle = substr($value['title'],1);
                }
            }
            $activeKeyArr=[];
            foreach ($value['child'] as $k=>$v){
                if($v['showkey']==1){
                    if($v['typeid']==3){
                        $keytitle = $v['poiname'];
                    }elseif($v['typeid']==2){
                        $keytitle = $v['cityname'];
                    }else{
                        $keytitle = $v['title'];
                    }

                    $activeKeyArr[] = [
                        'id'=>"name_".$v['id'],
                        'title'=>$keytitle,
                    ];
                }
            }
            $keyArr[] = [
                'day' => "DAY".($key+1)."：",
                'daytitle' => $daytitle,
                'day_key' => "day_".($key+1),
                'active' => $activeKeyArr
            ];
            if(!empty($value['thumb_map_img']) && $trip['show_day_map']==1) {
                $schedules[$key]['hasLine'] = true;
            }
        }
        $admin=db('admin')->find($trip['adminid']);
        if(!empty($admin)){
            $trip['admin']=$admin['nickname'];
            $trip['wx_qrcode']=$admin['wx_qrcode'];
        }else{
            $trip['admin']="";
            $trip['wx_qrcode']="";
        }

        $http = 'http://';
        if(isset($_SERVER['HTTPS']) && $_SERVER['HTTPS']=='on'){
            $http = 'https://';
        }

        $adminid= Cookie::get('admin');
        if(!empty($adminid)){
            $adminpwd=Db::name('admin')->where('id',$adminid)->select();
            $this->assign('url',$http.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'].'?prevadminpwd='.$adminpwd[0]['password']);
            $this->assign('pageurl',$http.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'].'?prevadminpwd='.$adminpwd[0]['password']);
            $this->assign('pwd',$adminpwd[0]['password']);
            $this->assign('nickname',$adminpwd[0]['nickname']);
            $this->assign('wordurl',$http.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'].'?prevadminpwd='.$adminpwd[0]['password']);
        }else{
            $prevadminpwd=$_GET['prevadminpwd'];
            $this->assign('url',$http.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
            $this->assign('pwd',$prevadminpwd);
            $this->assign('wordurl',$http.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
            $adminInfo = db('admin')->where('password',$prevadminpwd)->find();
            $this->assign('nickname',$adminInfo['nickname']??"");
        }
        $this->assign('baseurl',$http.$_SERVER['HTTP_HOST']);
        $this->assign('name',$trip['name']);
        $this->assign('allcity',$allcitys);
        $this->assign('scheduletime',[$schedules[0]['time'],$schedules[count($schedules)-1]['time']]);
        $this->assign('trip',$trip);
        $this->assign('keyArr',$keyArr);
        $this->assign('schedules',$schedules);
        //判断城市地图是否绘制
        $hasLine = false;
        if($trip['show_city_map']==1 && !empty($trip['thumb_map_img'])){
            $hasLine  = true;
        }
        $this->assign('hasLine',$hasLine);

        $activeTypeList = (new TripApi())->getGlobalActiveTypeList(false);
        $this->assign('activeTypeList',$activeTypeList);
        return $this->fetch();
    }

    public function price()
    {
        $id = $this->request->has('schedule_id') ? $this->request->param('schedule_id', 0, 'intval') : 0;
        $model=new scheduleModel();
        if ($id > 0) {
            if ($this->request->isPost()) {
                //是提交操作
                $post = $this->request->post();
                $save_data['price_json'] = $post['post_arr'];
                $save_data['count_price'] = $post['count_price'];

                if(false == $model->allowField(true)->save($save_data,['id'=>$id])) {
                    return $this->error('修改失败');
                } else {
                    return $this->success('修改成功', 'admin/menu/index');
                }
            }else{
                //展示
                $where_s['id'] = $id;
                $schedule_info = $model->where($where_s)->find();
                $count_price = $schedule_info['count_price'];

                $price_id_arr = array();
                $price_data = array();
                if($schedule_info['price_json'] && $schedule_info['price_json']!==''){
                    $price_arr = json_decode($schedule_info['price_json'],true);
                    foreach ($price_arr as $p_key=>$p_value) {
                        $price_id_arr[] = $p_value[0];
                        $price_data[$p_value[0]] = $p_value;
                    }
                }

                $price_id_str = implode(",",$price_id_arr);
                $where_id['price_type_id'] = array('in',$price_id_str);
                $info_id = Db::name('trip_price')->where($where_id)->field("price_type_id,pid")->select();

                $first_id_arr = array();
                foreach ($info_id as $key=>$value) {
                    if($value['pid']==0){
                        $first_id_arr[] = $value['price_type_id'];
                    }else{
                        $first_id_arr[] = $value['pid'];
                    }
                }

                $where['pid'] = 0;
                $info = Db::name('trip_price')->where($where)->select();

                $final_arr = array();
                $pid_arr = array();
                foreach ($info as $k=>$v) {
                    if($v['type_status']==2 && !in_array($v['price_type_id'],$first_id_arr)){//禁用状态
                        continue;
                    }

                    $final_arr[$v['price_type_id']] = $v;
                    $final_arr[$v['price_type_id']]['child'] = array();
                    $final_arr[$v['price_type_id']]['child_flag'] = 0;
                    $final_arr[$v['price_type_id']]['num'] = 0;
                    $pid_arr[] = $v['price_type_id'];

                    if(in_array($v['price_type_id'],$price_id_arr)){//已经存在设定值
                        $final_arr[$v['price_type_id']]['value'] = $price_data[$v['price_type_id']][1];
                        $final_arr[$v['price_type_id']]['num'] = $price_data[$v['price_type_id']][2];
                    }
                }

                $where1['pid'] = array("GT",0);
                $child_info = Db::name('trip_price')->where($where1)->select();
                foreach ($child_info as $k=>$v) {
                    $pid = $v['pid'];
                    if(in_array($pid,$pid_arr)){
                        $v['num'] = 0;
                        if(in_array($v['price_type_id'],$price_id_arr)){//已经存在设定值
                            $v['value'] = $price_data[$v['price_type_id']][1];
                            $v['num'] = $price_data[$v['price_type_id']][2];
                        }

                        $final_arr[$pid]['child'][] = $v;
                        $final_arr[$pid]['child_flag'] = 1;
                    }
                }

                $this->assign('schedule_id', $id);
                $this->assign('count_price', $count_price);
                $this->assign('info', $final_arr);
                return $this->fetch();
            }
        }
    }

    //修改行程选择车型
    public function changeCarType(){
        $post = $this->request->post();
        $id = $post['id'];
        $carType = $post['carType'];

        db('trip')->where('id', $id)->update(['carType' =>$carType]);
        return $this->success('修改成功');
    }

    //获取机场
    public function kbxGetAirport($cityname='')
    {
        $post = $this->request->post();
        if($post){
            $cityname = $post['cityname'];
        }
        $city = db("city")->where("name",$cityname)->field("kbx_id")->find();

        $kbxToken = new KbxToken();
        $url = $kbxToken->url.'/cities/'.$city['kbx_id'].'/airports';
        $token = 'Bearer ' . $kbxToken->kbxToken();
        $res = $kbxToken->get_data($url, $token);
        $res = $kbxToken->object_array($res);

        $data = [
            'code'=>1,
            'data'=>$res,
        ];

        return $data;
    }

    //包车价格核算  接口  组装数据
    public function orderPriceData($id)
    {
        $trip = Db::name('trip')->where('id',$id)->find();
        //车型
        $carType = isset($trip['carType']) ? $trip['carType'] : '';

        $resArr = [];
        $schedule = Db::name('schedule')->where('groupid',$id)->order('displayorder')->select();
        if(count($schedule)>0){
            for($day=0;$day<count($schedule);$day++){
                $active = Db::name('active')
                    ->alias('a')
                    ->join('city c','a.cityid=c.id','left')
                    ->where('a.groupid',$schedule[$day]['id'])
                    ->field("a.*,c.kbx_id as cityId,c.lat,c.lng")
                    ->order('a.displayorder')->select();

                $dayArr = [];
                foreach ($active as $k=>$v) {
                    $vArr = [];
                    $vArr['id'] = $v['id'];
                    $vArr['city'] = ['cityId'=>$v['cityId'],'lat'=>$v['lat'],'lng'=>$v['lng']];
                    $vArr['portType'] = isset($v['portType']) ? $v['portType'] : '';
                    $vArr['airportPlace'] = isset($v['airportPlace']) ? $v['airportPlace'] : '';
                    $vArr['time'] = $v['time'];
                    $vArr['arrival_time'] = isset($v['arrival_time']) ? $v['arrival_time'] : '';

                    if(!empty($v['poiid'])){//存在poi时
                        $poiData = Db::name('poi')->where('id',$v['poiid'])->find();
                        $poi_lat = $poiData['lat'];
                        $poi_lng = $poiData['lng'];
                        $vArr['location'] = ['lat'=>$poi_lat,'lng'=>$poi_lng];
                    }else{
                        $vArr['location'] = ['lat'=>$v['lat'],'lng'=>$v['lng']];
                    }

                    if($vArr['portType']!==''){
                        if($vArr['portType']=='Transport_Vehicle_FromAirport'){//接机
                            $dayArr['fromAirport'][] = $vArr;
                        }elseif($vArr['portType']=='Transport_Vehicle_ToAirport'){//送机
                            $vArr['arrival_time'] = $vArr['time'];
                            $dayArr['toAirport'][] = $vArr;
                        }elseif($vArr['portType']=='Transport_Vehicle_HalfDay'){//市区半日包车
                            $dayArr['halfDay'][] = $vArr;
                        }elseif($vArr['portType']=='Transport_Vehicle_OneDay'){//市区一日包车
                            $dayArr['oneDay'][] = $vArr;
                        }elseif($vArr['portType']=='Transport_Vehicle_Around'){//周边一日包车
                            $dayArr['aroundDay'][] = $vArr;
                        }
                    }else{
                        continue;
                    }
                }

                $finalDay = [];
                $finalDay['id'] = $schedule[$day]['id'];
                $finalDay['time'] = $schedule[$day]['time'];
                $finalDay['activities'] = [];
                foreach ($dayArr as $key=>$value) {
                    $activities = [];
                    //接送机
                    if($key=='fromAirport' || $key=='toAirport'){
                        $activities['id'] = $value[0]['id'];
                        $activities['type'] = $value[0]['portType'];
                        $activities['carType'] = $carType;
                        $activities['city'] = $value[0]['city']['cityId'];
                        $activities['from'] = [
                            'city'=>$activities['city'],
                            'placeId'=>$value[0]['airportPlace'],
                            'location'=>[
                                'lat'=>$value[0]['city']['lat'],
                                'lng'=>$value[0]['city']['lng']
                            ]
                        ];
                        $activities['to'] = $activities['from'];
                        $activities['pois'] = [];
                    }else{//包车
                        $activities['id'] = $value[0]['id'];
                        $activities['type'] = $value[0]['portType'];
                        $activities['carType'] = $carType;
                        $activities['city'] = $value[0]['city']['cityId'];
                        $activities['from'] = [
                            'city'=>$activities['city'],
                            'location'=>[
                                'lat'=>$value[0]['city']['lat'],
                                'lng'=>$value[0]['city']['lng']
                            ]
                        ];

                        array_shift($value);
                        if(count($value)>0){
                            $lastActivity = array_pop($value);
                            $activities['to'] = [
                                'city'=>$lastActivity['city']['cityId'],
                                'location'=>[
                                    'lat'=>$lastActivity['city']['lat'],
                                    'lng'=>$lastActivity['city']['lng']
                                ]
                            ];
                        }else{
                            $activities['to'] = $activities['from'];
                        }

                        $activities['pois'] = [];
                        if(!empty($value)){
                            foreach ($value as $k=>$v) {
                                $activities['pois'][] = ['location'=>$v['location']];
                            }
                        }
                    }
                    $finalDay['activities'][] = $activities;
                }
                $resArr[] = $finalDay;
            }
        }

        return $resArr;
    }

    //临时使用
    //查看返回json数据
    public function jsonPrice(){
        $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;

        //封装数据
        $post_data = $this->orderPriceData($id);

        //调用接口查询价格
        $KbxOther = new KbxOther();
        $priceData = $KbxOther->getCarPrice(['fullTravel'=>$post_data]);

        $data = json_decode($priceData,true);

        foreach ($data as $k=>$v) {
            $totalPrice = 0;
            $data[$k]['a_num'] = count($v['activities']);
            foreach ($v['activities'] as $k_a=>$v_a) {
                if(!empty($v_a['distance'])){
                    $data[$k]['activities'][$k_a]['distance'] = round($v_a['distance']/1000,2);
                }
                if(!empty($v_a['duration'])){
                    $data[$k]['activities'][$k_a]['duration'] = round($v_a['duration']/3600,2);
                }
                if(!empty($v_a['totalAmount'])){
                    $totalPrice += $v_a['totalAmount'];
                }

                $cityStr = '';
                if(!empty($v_a['from']['city'])){
                    $fromCityId = $v_a['from']['city'];
                    $toCityId = $v_a['to']['city'];

                    $fromData = db("city")->where("kbx_id",$fromCityId)->field("name")->find();
                    $toData = db("city")->where("kbx_id",$toCityId)->field("name")->find();

                    $fromCity = $fromData['name'];
                    $toCity = $toData['name'];

                    if($fromCity==$toCity){
                        $cityStr = $fromCity;
                    }else{
                        $cityStr = $fromCity." - ".$toCity;
                    }
                }
                $data[$k]['activities'][$k_a]['cityStr'] = $cityStr;
            }
            $data[$k]['totalPrice'] = $totalPrice;
        }

        echo "<pre>";
        var_dump($data);
        echo "</pre>";

        return $this->fetch();
    }

    //计算行程价格
    public function countTripPrice(){

//        error_reporting(E_ERROR);

        $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;

        //封装数据
        $post_data = $this->orderPriceData($id);

        //调用接口查询价格
        $KbxOther = new KbxOther();
        $priceData = $KbxOther->getCarPrice(['fullTravel'=>$post_data]);
        $data = json_decode($priceData,true);

        //获取汇率
        $exchange = db("exchange")->select();

        $ex_USD = 1;//美元转人民币
        $ex_CAD = 1;//加币转人民币
        foreach ($exchange as $k=>$v) {
            if($v['currency_code']=='USD'){
                $ex_USD = $v['exchange_rate'];
            }elseif($v['currency_code']=='CAD'){
                $ex_CAD = $v['exchange_rate'];
            }
        }

        foreach ($data as $k=>$v) {
            $totalPrice = 0;
            $data[$k]['a_num'] = count($v['activities']);

            $schedule_id = $v['id'];
            $schedule_data = db("schedule")->where("id",$schedule_id)->field("changePrice")->find();
            $changePrice = $schedule_data['changePrice'];
            $data[$k]['changePrice'] = !empty($changePrice) ? $changePrice : '';

            foreach ($v['activities'] as $k_a=>$v_a) {
                if(!empty($v_a['id'])){
                    $activity_id = $v_a['id'];
                    $activity = db("active")->where("id",$activity_id)->field("tickitPrice,goodsPrice,goods_id,tickitBuyDetails")->find();

                    if(!empty($activity['goods_id'])){
                        $goods_id = $activity['goods_id'];
                        $goods = db("goods")->where("goods_id",$goods_id)->field("goods_name")->find();
                        $goods_name = $goods['goods_name'];
                        $goodsPrice = $activity['goodsPrice'];

                        if($goodsPrice!==''){
                            $totalPrice += $goodsPrice;
                        }

                        $data[$k]['activities'][$k_a]['goodsStr'] = "商品购买详情：".$goods_name."<br>"."商品购买价格：￥".$goodsPrice;
                    }else{
                        $data[$k]['activities'][$k_a]['goodsStr'] = '';
                    }

                    $tickitPrice = !empty($activity['tickitPrice']) ? $activity['tickitPrice'] : '';
                    $tickitBuyDetails = !empty($activity['tickitBuyDetails']) ? $activity['tickitBuyDetails'] : '';

                    if($tickitPrice!==''){
                        $totalPrice += $tickitPrice;
                    }

                    if($tickitPrice!=='' || $tickitBuyDetails!==''){
                        $data[$k]['activities'][$k_a]['tickitStr'] = "门票购买详情：".$tickitBuyDetails."<br>"."门票购买价格：￥".$tickitPrice;
                    }else{
                        $data[$k]['activities'][$k_a]['tickitStr'] = '';
                    }
                }else{
                    $data[$k]['activities'][$k_a]['goodsStr'] = '';
                    $data[$k]['activities'][$k_a]['tickitStr'] = '';
                }

                if(!empty($v_a['distance'])){
                    $data[$k]['activities'][$k_a]['distance'] = round($v_a['distance']/1000,2);
                }
                if(!empty($v_a['duration'])){
                    $data[$k]['activities'][$k_a]['duration'] = round($v_a['duration']/3600,2);
                }
                if(!empty($v_a['totalAmount'])){
                    $totalPrice += $v_a['totalAmount'];
                }

                $cityStr = '';
                if(!empty($v_a['from']['city'])) {
                    $fromCityId = $v_a['from']['city'];
                    $toCityId = $v_a['to']['city'];

                    $fromData = db("city")->where("kbx_id",$fromCityId)->field("name")->find();
                    $toData = db("city")->where("kbx_id",$toCityId)->field("name")->find();

                    $fromCity = $fromData['name'];
                    $toCity = $toData['name'];

                    if($fromCity==$toCity){
                        $cityStr = $fromCity;
                    }else{
                        $cityStr = $fromCity."<br> - <br>".$toCity;
                    }
                }
                $data[$k]['activities'][$k_a]['cityStr'] = $cityStr;
            }

            if(!empty($changePrice)){
                $totalPrice += $changePrice;
            }

            $data[$k]['totalPrice'] = $totalPrice;

            $totalPrice_USD = ceil($totalPrice/$ex_USD);//美元价格
            $totalPrice_CAD = ceil($totalPrice/$ex_CAD);//加币价格


            $data[$k]['totalPrice_USD'] = $totalPrice_USD;
            $data[$k]['totalPrice_CAD'] = $totalPrice_CAD;
        }


        $tripData = db("trip")->where("id",$id)->field("ratio")->find();
        $ratio = $tripData['ratio'];

        $this->assign('trip_id',$id);
        $this->assign('ratio',$ratio);
        $this->assign('ex_USD',$ex_USD);
        $this->assign('ex_CAD',$ex_CAD);
        $this->assign('priceData',$data);

        return $this->fetch();
    }

    //行程核价  记录调整价格
    public function saveChangePrice(){
        $post = $this->request->post();
        $str = $post['str'];
        $p_str = $post['p_str'];
        $data = explode(",",$str);
        $ratio = $post['ratio'];
        $trip_id = $post['trip_id'];

        foreach ($data as $key=>$value){
            if(!empty($value)){
                $v_arr = explode("_",$value);
                db('schedule')->where('id', $v_arr[0])->update(['changePrice' =>$v_arr[1]]);
            }
        }

        $p_data = explode(",",$p_str);
        foreach ($p_data as $key=>$value){
            if(!empty($value)){
                $v_arr = explode("_",$value);
                db('schedule')->where('id', $v_arr[0])->update(['dayPrice' =>$v_arr[1]]);
            }
        }

        db('trip')->where('id',$trip_id)->update(['ratio' =>$ratio]);

        return $this->success('保存成功');
    }

    //开启&关闭  索引
    public function changeShowkey(){
        $post = $this->request->post();
        $id = $post['id'];
        $key = $post['key'];
        if($key==1){
            $showkey = 0;
        }else{
            $showkey = 1;
        }

        db('active')->where('id', $id)->update(['showkey' =>$showkey]);

        return $this->success('修改成功');
    }

    //查询POI的tickit信息
    public function getTickit(){
        $post = $this->request->post();
        $id = $post['id'];
        $tickit = db('poi')->where('id', $id)->field("groupid,thumb,tickit,tickitDetails,introduce")->find();

        $poiImg = [];
        if(!empty($tickit['thumb'])){
            $poi_thumbArr = explode(",",$tickit['thumb']);
            $poi_thumbArr = array_filter($poi_thumbArr);
            $img1 = array_shift($poi_thumbArr);
            $img2 = array_shift($poi_thumbArr);
            if(!empty($img1)){
                $poiImg[] = $img1;
            }
            if(!empty($img2)){
                $poiImg[] = $img2;
            }
        }
        if(!empty($tickit['groupid'])){
            $cityname = db("city")->field('name')->find($tickit['groupid']);
            $cityname = $cityname['name']??"";
        }else{
            $cityname = "";
        }
        $data = [
            'tickit'=>$tickit,
            'poiImg'=>$poiImg,
            'cityname'=>$cityname
        ];

        return $this->success('查询结果','',$data);
    }

    //FAQ编辑  废弃
    public function faq()
    {
        $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
        $model=new tripModel();
        if($id > 0) {
            //修改操作
            if($this->request->isPost()) {
                //是提交操作
                $post = $this->request->post();

                if(false == $model->allowField(true)->save($post,['id'=>$id])) {
                    return $this->error('修改失败');
                } else {
                    return $this->success('修改成功', 'admin/menu/index');
                }
            } else {
                //非提交操作
                $trip = Db::name('trip')->where('id',$id)->find();

                if(!empty($trip)) {
                    $this->assign('menu',$trip);
                    return $this->fetch();
                } else {
                    return $this->error('id不正确');
                }
            }
        }else{
            return $this->error('id不正确');
        }
    }

    //查询poi
    public function searchPoi()
    {
        $post = request()->post();
        $where['deleted'] = 0;
        if(isset($post['key'])){
            $key = $post['key'];
            $where['name'] = ['like','%'.$key.'%'];
            $list = db("poi")->where($where)->field("id,name")->order("id desc")->select();
        }else{
            $list = db("poi")->where($where)->field("id,name")->order("id desc")->select();
        }

        return json(['code'=>200,'msg'=>'获取列表成功','data'=>$list]);
    }

    //图片库
    public function addpoiimg(){
        $poi_id = input("id");
        $where['poi_id'] = $poi_id;
        $page = input('page');
        $tob_type = input('tob_type');//toB平台
        $tob_type = !empty($tob_type) ? $tob_type : 0;
        $page = empty($page)?1:$page;
        $imgArr = db("poi_images")->where($where)->order("show desc,id desc")->paginate(20);
        $poiImgs = db("poi")->field("thumb")->where(['id'=>$poi_id])->find();
        $poiimgArr= array_filter(explode(",",$poiImgs['thumb']));

        $this->assign('tob_type',$tob_type);
        $this->assign('poi_id',$poi_id);
        $this->assign('imgArr',$imgArr);
        $this->assign('poiimgArr',$poiimgArr);
        return $this->fetch();
    }

    //查询POI初始设置图片
    public function getPoiImg(){
        $post = $this->request->post();
        $poitype = $post['poitype'];
        $cityname = $post['cityname'];
        $city = Db::name('city')->where('name',$cityname)->where('deleted',0)->find();
        $cityid = $city['id'];

        $where['deleted'] = 0;
        $where['groupid'] = $cityid;
        if ($poitype == 1) {
            $where['typeid'] = 1;
        } elseif ($poitype == 2) {
            $where['typeid'] = 5;
        } else {
            $where['typeid'] = ["in",[2, 3, 4, 6]];
        }
        $poi = db('poi')->where($where)->field("thumb")->find();

        $poiImg = [];
        if(!empty($poi['thumb'])){
            $poi_thumbArr = explode(",",$poi['thumb']);
            $poi_thumbArr = array_filter($poi_thumbArr);
            $img1 = array_shift($poi_thumbArr);
            $img2 = array_shift($poi_thumbArr);
            if(!empty($img1)){
                $poiImg[] = $img1;
            }
            if(!empty($img2)){
                $poiImg[] = $img2;
            }
        }

        $data = [
            'poiImg'=>$poiImg,
        ];

        return $this->success('查询结果','',$data);
    }

    //清空文件夹函数和清空文件夹后删除空文件夹函数的处理
    protected function deldir($path){
        //如果是目录则继续
        if(is_dir($path)){
            //扫描一个文件夹内的所有文件夹和文件并返回数组
            $p = scandir($path);
            foreach($p as $val){
                //排除目录中的.和..
                if($val !="." && $val !=".."){
                    //如果是目录则递归子目录，继续操作
                    if(is_dir($path.$val)){
                        //子目录中操作删除文件夹和文件
                        $this->deldir($path.$val.'/');
                        //目录清空后删除空文件夹
                        @rmdir($path.$val.'/');
                    }else{
                        //如果是文件直接删除
                        unlink($path.$val);
                    }
                }
            }
        }
    }
    //删除缓存的文件
    protected function delTripImgDir($imgdir)
    {
//        $rootpath = '/var/www/html/php_test_station/fast_bank/';
        $rootpath = ROOT_PATH;
        $testDir = Config::get('baseTempImgDir');
        $dir = $rootpath.'public'.DS.$testDir.DS.'t_'.$imgdir.DS;
        $this->deldir($dir);
    }

}
